--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/016-llvm-21851513-memory-corruption.patch Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,3107 @@
+# 21851513 severe memory corruption in the LLVM command-line parsing module
+# 21870103 TableGen makes incorrect assumptions about anonymous namespace instantiation
+# 21870087 naming convention for the InputFile key is inconsistent across LLVM utilities
+# 21870099 128 bytes for a filesystem path is definitely not enough
+# clang makes incorrect assumptions about anonymous namespace instantiation order
+# For upstream - maybe.
+--- include/llvm/Support/ThreadLocal.h 2014-12-14 17:04:45.000000000 -0800
++++ include/llvm/Support/ThreadLocal.h 2015-09-16 14:08:58.000000000 -0700
+@@ -21,24 +21,22 @@
+ namespace llvm {
+ namespace sys {
+ // ThreadLocalImpl - Common base class of all ThreadLocal instantiations.
+ // YOU SHOULD NEVER USE THIS DIRECTLY.
+ class ThreadLocalImpl {
+ typedef uint64_t ThreadLocalDataTy;
+ /// \brief Platform-specific thread local data.
+ ///
+ /// This is embedded in the class and we avoid malloc'ing/free'ing it,
+ /// to make this class more safe for use along with CrashRecoveryContext.
+- union {
+- char data[sizeof(ThreadLocalDataTy)];
+- ThreadLocalDataTy align_data;
+- };
++ uint64_t data[2];
++
+ public:
+ ThreadLocalImpl();
+ virtual ~ThreadLocalImpl();
+ void setInstance(const void* d);
+ void *getInstance();
+ void removeInstance();
+ };
+
+ /// ThreadLocal - A class used to abstract thread-local storage. It holds,
+ /// for each thread, a pointer a single object of type T.
+--- lib/Support/MemoryBuffer.cpp 2014-12-12 14:27:53.000000000 -0800
++++ lib/Support/MemoryBuffer.cpp 2015-09-19 14:20:06.472430028 -0700
+@@ -21,25 +21,29 @@
+ #include "llvm/Support/Path.h"
+ #include "llvm/Support/Process.h"
+ #include "llvm/Support/Program.h"
+ #include <cassert>
+ #include <cerrno>
+ #include <cstdio>
+ #include <cstring>
+ #include <new>
+ #include <sys/types.h>
+ #include <system_error>
++
+ #if !defined(_MSC_VER) && !defined(__MINGW32__)
+ #include <unistd.h>
+ #else
+ #include <io.h>
+ #endif
++
++#include <climits>
++
+ using namespace llvm;
+
+ //===----------------------------------------------------------------------===//
+ // MemoryBuffer implementation itself.
+ //===----------------------------------------------------------------------===//
+
+ MemoryBuffer::~MemoryBuffer() { }
+
+ /// init - Initialize this MemoryBuffer as a reference to externally allocated
+ /// memory, memory that we know is already null terminated.
+@@ -63,21 +67,21 @@
+ }
+
+ namespace {
+ struct NamedBufferAlloc {
+ const Twine &Name;
+ NamedBufferAlloc(const Twine &Name) : Name(Name) {}
+ };
+ }
+
+ void *operator new(size_t N, const NamedBufferAlloc &Alloc) {
+- SmallString<256> NameBuf;
++ SmallString<PATH_MAX> NameBuf;
+ StringRef NameRef = Alloc.Name.toStringRef(NameBuf);
+
+ char *Mem = static_cast<char *>(operator new(N + NameRef.size() + 1));
+ CopyStringRef(Mem + N, NameRef);
+ return Mem;
+ }
+
+ namespace {
+ /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
+ class MemoryBufferMem : public MemoryBuffer {
+@@ -156,21 +160,21 @@
+ MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
+ std::unique_ptr<MemoryBuffer> SB = getNewUninitMemBuffer(Size, BufferName);
+ if (!SB)
+ return nullptr;
+ memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
+ return SB;
+ }
+
+ ErrorOr<std::unique_ptr<MemoryBuffer>>
+ MemoryBuffer::getFileOrSTDIN(const Twine &Filename, int64_t FileSize) {
+- SmallString<256> NameBuf;
++ SmallString<PATH_MAX> NameBuf;
+ StringRef NameRef = Filename.toStringRef(NameBuf);
+
+ if (NameRef == "-")
+ return getSTDIN();
+ return getFile(Filename, FileSize);
+ }
+
+ ErrorOr<std::unique_ptr<MemoryBuffer>>
+ MemoryBuffer::getFileSlice(const Twine &FilePath, uint64_t MapSize,
+ uint64_t Offset) {
+--- lib/Support/Unix/Program.inc 2014-12-01 16:52:01.000000000 -0800
++++ lib/Support/Unix/Program.inc 2015-09-19 15:34:57.144042911 -0700
+@@ -31,23 +31,20 @@
+ #if HAVE_SIGNAL_H
+ #include <signal.h>
+ #endif
+ #if HAVE_FCNTL_H
+ #include <fcntl.h>
+ #endif
+ #if HAVE_UNISTD_H
+ #include <unistd.h>
+ #endif
+ #ifdef HAVE_POSIX_SPAWN
+-#ifdef __sun__
+-#define _RESTRICT_KYWD
+-#endif
+ #include <spawn.h>
+ #if !defined(__APPLE__)
+ extern char **environ;
+ #else
+ #include <crt_externs.h> // _NSGetEnviron
+ #endif
+ #endif
+
+ namespace llvm {
+
+--- lib/TableGen/Main.cpp 2014-12-10 23:04:54.000000000 -0800
++++ lib/TableGen/Main.cpp 2015-09-19 18:04:08.147911223 -0700
+@@ -21,97 +21,118 @@
+ #include "llvm/Support/MemoryBuffer.h"
+ #include "llvm/Support/ToolOutputFile.h"
+ #include "llvm/TableGen/Error.h"
+ #include "llvm/TableGen/Main.h"
+ #include "llvm/TableGen/Record.h"
+ #include <algorithm>
+ #include <cstdio>
+ #include <system_error>
+ using namespace llvm;
+
+-namespace {
+- cl::opt<std::string>
+- OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"),
+- cl::init("-"));
+-
+- cl::opt<std::string>
+- DependFilename("d",
+- cl::desc("Dependency filename"),
+- cl::value_desc("filename"),
+- cl::init(""));
+-
+- cl::opt<std::string>
+- InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
+-
+- cl::list<std::string>
+- IncludeDirs("I", cl::desc("Directory of include files"),
+- cl::value_desc("directory"), cl::Prefix);
+-}
++static cl::opt<std::string>
++OutputFilename(cl::Prefix, "o",
++ cl::desc("Output filename"),
++ cl::value_desc("filename"),
++ cl::NotHidden,
++ cl::Optional,
++ cl::init("-"),
++ cl::ValueRequired);
++
++static cl::opt<std::string>
++DependFilename(cl::Prefix, "d",
++ cl::desc("Dependency filename"),
++ cl::value_desc("filename"),
++ cl::NotHidden,
++ cl::Optional,
++ cl::init(""),
++ cl::ValueRequired);
++
++static cl::opt<std::string>
++InputFilename(cl::Positional, "<input file>",
++ cl::desc("<input file>"),
++ cl::value_desc("Input filename"),
++ cl::NotHidden,
++ cl::Optional,
++ cl::init("-"),
++ cl::ValuePositionalNoArgs);
++
++static cl::list<std::string>
++IncludeDirs(cl::Prefix, "I",
++ cl::desc("Directory of include files"),
++ cl::value_desc("directory"),
++ cl::NotHidden,
++ cl::ZeroOrMore,
++ cl::ValueRequired);
+
+ /// \brief Create a dependency file for `-d` option.
+ ///
+ /// This functionality is really only for the benefit of the build system.
+ /// It is similar to GCC's `-M*` family of options.
+ static int createDependencyFile(const TGParser &Parser, const char *argv0) {
+ if (OutputFilename == "-") {
+ errs() << argv0 << ": the option -d must be used together with -o\n";
+ return 1;
+ }
+ std::error_code EC;
+ tool_output_file DepOut(DependFilename, EC, sys::fs::F_Text);
+ if (EC) {
+ errs() << argv0 << ": error opening " << DependFilename << ":"
+ << EC.message() << "\n";
+ return 1;
+ }
++
+ DepOut.os() << OutputFilename << ":";
++
+ for (const auto &Dep : Parser.getDependencies()) {
+ DepOut.os() << ' ' << Dep.first;
+ }
+ DepOut.os() << "\n";
+ DepOut.keep();
+ return 0;
+ }
+
+ namespace llvm {
+
+ int TableGenMain(char *argv0, TableGenMainFn *MainFn) {
+ RecordKeeper Records;
+
+ // Parse the input file.
++ llvm::Twine TFN(InputFilename);
+ ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
+- MemoryBuffer::getFileOrSTDIN(InputFilename);
++ MemoryBuffer::getFileOrSTDIN(TFN);
++
+ if (std::error_code EC = FileOrErr.getError()) {
+ errs() << "Could not open input file '" << InputFilename
+- << "': " << EC.message() << "\n";
++ << "': " << EC.message() << "\n";
+ return 1;
+ }
+
+ // Tell SrcMgr about this buffer, which is what TGParser will pick up.
+ SrcMgr.AddNewSourceBuffer(std::move(*FileOrErr), SMLoc());
+
+ // Record the location of the include directory so that the lexer can find
+ // it later.
+- SrcMgr.setIncludeDirs(IncludeDirs);
++ SrcMgr.setIncludeDirs(IncludeDirs.getStorage());
+
+ TGParser Parser(SrcMgr, Records);
+
+ if (Parser.ParseFile())
+ return 1;
+
+ std::error_code EC;
+ tool_output_file Out(OutputFilename, EC, sys::fs::F_Text);
+ if (EC) {
+ errs() << argv0 << ": error opening " << OutputFilename << ":"
+ << EC.message() << "\n";
+ return 1;
+ }
++
+ if (!DependFilename.empty()) {
+ if (int Ret = createDependencyFile(Parser, argv0))
+ return Ret;
+ }
+
+ if (MainFn(Out.os(), Records))
+ return 1;
+
+ if (ErrorsPrinted > 0) {
+ errs() << argv0 << ": " << ErrorsPrinted << " errors.\n";
+--- utils/TableGen/TableGen.cpp 2014-12-10 23:04:54.000000000 -0800
++++ utils/TableGen/TableGen.cpp 2015-09-14 16:23:45.000000000 -0700
+@@ -37,67 +37,67 @@
+ GenFastISel,
+ GenSubtarget,
+ GenIntrinsic,
+ GenTgtIntrinsic,
+ PrintEnums,
+ PrintSets,
+ GenOptParserDefs,
+ GenCTags
+ };
+
+-namespace {
+- cl::opt<ActionType>
+- Action(cl::desc("Action to perform:"),
+- cl::values(clEnumValN(PrintRecords, "print-records",
+- "Print all records to stdout (default)"),
+- clEnumValN(GenEmitter, "gen-emitter",
+- "Generate machine code emitter"),
+- clEnumValN(GenRegisterInfo, "gen-register-info",
+- "Generate registers and register classes info"),
+- clEnumValN(GenInstrInfo, "gen-instr-info",
+- "Generate instruction descriptions"),
+- clEnumValN(GenCallingConv, "gen-callingconv",
+- "Generate calling convention descriptions"),
+- clEnumValN(GenAsmWriter, "gen-asm-writer",
+- "Generate assembly writer"),
+- clEnumValN(GenDisassembler, "gen-disassembler",
+- "Generate disassembler"),
+- clEnumValN(GenPseudoLowering, "gen-pseudo-lowering",
+- "Generate pseudo instruction lowering"),
+- clEnumValN(GenAsmMatcher, "gen-asm-matcher",
+- "Generate assembly instruction matcher"),
+- clEnumValN(GenDAGISel, "gen-dag-isel",
+- "Generate a DAG instruction selector"),
+- clEnumValN(GenDFAPacketizer, "gen-dfa-packetizer",
+- "Generate DFA Packetizer for VLIW targets"),
+- clEnumValN(GenFastISel, "gen-fast-isel",
+- "Generate a \"fast\" instruction selector"),
+- clEnumValN(GenSubtarget, "gen-subtarget",
+- "Generate subtarget enumerations"),
+- clEnumValN(GenIntrinsic, "gen-intrinsic",
+- "Generate intrinsic information"),
+- clEnumValN(GenTgtIntrinsic, "gen-tgt-intrinsic",
+- "Generate target intrinsic information"),
+- clEnumValN(PrintEnums, "print-enums",
+- "Print enum values for a class"),
+- clEnumValN(PrintSets, "print-sets",
+- "Print expanded sets for testing DAG exprs"),
+- clEnumValN(GenOptParserDefs, "gen-opt-parser-defs",
+- "Generate option definitions"),
+- clEnumValN(GenCTags, "gen-ctags",
+- "Generate ctags-compatible index"),
+- clEnumValEnd));
++static cl::opt<ActionType>
++Action(cl::desc("Action to perform:"),
++ cl::values(clEnumValN(PrintRecords, "print-records",
++ "Print all records to stdout (default)"),
++ clEnumValN(GenEmitter, "gen-emitter",
++ "Generate machine code emitter"),
++ clEnumValN(GenRegisterInfo, "gen-register-info",
++ "Generate registers and register classes info"),
++ clEnumValN(GenInstrInfo, "gen-instr-info",
++ "Generate instruction descriptions"),
++ clEnumValN(GenCallingConv, "gen-callingconv",
++ "Generate calling convention descriptions"),
++ clEnumValN(GenAsmWriter, "gen-asm-writer",
++ "Generate assembly writer"),
++ clEnumValN(GenDisassembler, "gen-disassembler",
++ "Generate disassembler"),
++ clEnumValN(GenPseudoLowering, "gen-pseudo-lowering",
++ "Generate pseudo instruction lowering"),
++ clEnumValN(GenAsmMatcher, "gen-asm-matcher",
++ "Generate assembly instruction matcher"),
++ clEnumValN(GenDAGISel, "gen-dag-isel",
++ "Generate a DAG instruction selector"),
++ clEnumValN(GenDFAPacketizer, "gen-dfa-packetizer",
++ "Generate DFA Packetizer for VLIW targets"),
++ clEnumValN(GenFastISel, "gen-fast-isel",
++ "Generate a \"fast\" instruction selector"),
++ clEnumValN(GenSubtarget, "gen-subtarget",
++ "Generate subtarget enumerations"),
++ clEnumValN(GenIntrinsic, "gen-intrinsic",
++ "Generate intrinsic information"),
++ clEnumValN(GenTgtIntrinsic, "gen-tgt-intrinsic",
++ "Generate target intrinsic information"),
++ clEnumValN(PrintEnums, "print-enums",
++ "Print enum values for a class"),
++ clEnumValN(PrintSets, "print-sets",
++ "Print expanded sets for testing DAG exprs"),
++ clEnumValN(GenOptParserDefs, "gen-opt-parser-defs",
++ "Generate option definitions"),
++ clEnumValN(GenCTags, "gen-ctags",
++ "Generate ctags-compatible index"),
++ clEnumValEnd));
+
+- cl::opt<std::string>
+- Class("class", cl::desc("Print Enum list for this class"),
+- cl::value_desc("class name"));
++static cl::opt<std::string>
++Class("class", cl::desc("Print Enum list for this class"),
++ cl::value_desc("class name"));
+
++namespace {
+ bool LLVMTableGenMain(raw_ostream &OS, RecordKeeper &Records) {
+ switch (Action) {
+ case PrintRecords:
+ OS << Records; // No argument, dump all contents
+ break;
+ case GenEmitter:
+ EmitCodeEmitter(Records, OS);
+ break;
+ case GenRegisterInfo:
+ EmitRegisterInfo(Records, OS);
+--- tools/clang/utils/TableGen/TableGen.cpp 2015-09-19 19:30:26.983452195 -0700
++++ tools/clang/utils/TableGen/TableGen.cpp 2015-09-19 23:12:38.299907988 -0700
+@@ -48,101 +48,99 @@
+ GenClangCommentHTMLTagsProperties,
+ GenClangCommentHTMLNamedCharacterReferences,
+ GenClangCommentCommandInfo,
+ GenClangCommentCommandList,
+ GenArmNeon,
+ GenArmNeonSema,
+ GenArmNeonTest,
+ GenAttrDocs
+ };
+
+-namespace {
+-cl::opt<ActionType> Action(
+- cl::desc("Action to perform:"),
+- cl::values(
+- clEnumValN(GenClangAttrClasses, "gen-clang-attr-classes",
+- "Generate clang attribute clases"),
+- clEnumValN(GenClangAttrParserStringSwitches,
+- "gen-clang-attr-parser-string-switches",
+- "Generate all parser-related attribute string switches"),
+- clEnumValN(GenClangAttrImpl, "gen-clang-attr-impl",
+- "Generate clang attribute implementations"),
+- clEnumValN(GenClangAttrList, "gen-clang-attr-list",
+- "Generate a clang attribute list"),
+- clEnumValN(GenClangAttrPCHRead, "gen-clang-attr-pch-read",
+- "Generate clang PCH attribute reader"),
+- clEnumValN(GenClangAttrPCHWrite, "gen-clang-attr-pch-write",
+- "Generate clang PCH attribute writer"),
+- clEnumValN(GenClangAttrHasAttributeImpl,
+- "gen-clang-attr-has-attribute-impl",
+- "Generate a clang attribute spelling list"),
+- clEnumValN(GenClangAttrSpellingListIndex,
+- "gen-clang-attr-spelling-index",
+- "Generate a clang attribute spelling index"),
+- clEnumValN(GenClangAttrASTVisitor,
+- "gen-clang-attr-ast-visitor",
+- "Generate a recursive AST visitor for clang attributes"),
+- clEnumValN(GenClangAttrTemplateInstantiate,
+- "gen-clang-attr-template-instantiate",
+- "Generate a clang template instantiate code"),
+- clEnumValN(GenClangAttrParsedAttrList,
+- "gen-clang-attr-parsed-attr-list",
+- "Generate a clang parsed attribute list"),
+- clEnumValN(GenClangAttrParsedAttrImpl,
+- "gen-clang-attr-parsed-attr-impl",
+- "Generate the clang parsed attribute helpers"),
+- clEnumValN(GenClangAttrParsedAttrKinds,
+- "gen-clang-attr-parsed-attr-kinds",
+- "Generate a clang parsed attribute kinds"),
+- clEnumValN(GenClangAttrDump, "gen-clang-attr-dump",
+- "Generate clang attribute dumper"),
+- clEnumValN(GenClangDiagsDefs, "gen-clang-diags-defs",
+- "Generate Clang diagnostics definitions"),
+- clEnumValN(GenClangDiagGroups, "gen-clang-diag-groups",
+- "Generate Clang diagnostic groups"),
+- clEnumValN(GenClangDiagsIndexName, "gen-clang-diags-index-name",
+- "Generate Clang diagnostic name index"),
+- clEnumValN(GenClangCommentNodes, "gen-clang-comment-nodes",
+- "Generate Clang AST comment nodes"),
+- clEnumValN(GenClangDeclNodes, "gen-clang-decl-nodes",
+- "Generate Clang AST declaration nodes"),
+- clEnumValN(GenClangStmtNodes, "gen-clang-stmt-nodes",
+- "Generate Clang AST statement nodes"),
+- clEnumValN(GenClangSACheckers, "gen-clang-sa-checkers",
+- "Generate Clang Static Analyzer checkers"),
+- clEnumValN(GenClangCommentHTMLTags, "gen-clang-comment-html-tags",
+- "Generate efficient matchers for HTML tag "
+- "names that are used in documentation comments"),
+- clEnumValN(GenClangCommentHTMLTagsProperties,
+- "gen-clang-comment-html-tags-properties",
+- "Generate efficient matchers for HTML tag "
+- "properties"),
+- clEnumValN(GenClangCommentHTMLNamedCharacterReferences,
+- "gen-clang-comment-html-named-character-references",
+- "Generate function to translate named character "
+- "references to UTF-8 sequences"),
+- clEnumValN(GenClangCommentCommandInfo, "gen-clang-comment-command-info",
+- "Generate command properties for commands that "
+- "are used in documentation comments"),
+- clEnumValN(GenClangCommentCommandList, "gen-clang-comment-command-list",
+- "Generate list of commands that are used in "
+- "documentation comments"),
+- clEnumValN(GenArmNeon, "gen-arm-neon", "Generate arm_neon.h for clang"),
+- clEnumValN(GenArmNeonSema, "gen-arm-neon-sema",
+- "Generate ARM NEON sema support for clang"),
+- clEnumValN(GenArmNeonTest, "gen-arm-neon-test",
+- "Generate ARM NEON tests for clang"),
+- clEnumValN(GenAttrDocs, "gen-attr-docs",
+- "Generate attribute documentation"),
+- clEnumValEnd));
++static cl::opt<ActionType>
++Action(cl::desc("Action to perform:"),
++ cl::values(clEnumValN(GenClangAttrClasses, "gen-clang-attr-classes",
++ "Generate clang attribute clases"),
++ clEnumValN(GenClangAttrParserStringSwitches,
++ "gen-clang-attr-parser-string-switches",
++ "Generate all parser-related attribute string switches"),
++ clEnumValN(GenClangAttrImpl, "gen-clang-attr-impl",
++ "Generate clang attribute implementations"),
++ clEnumValN(GenClangAttrList, "gen-clang-attr-list",
++ "Generate a clang attribute list"),
++ clEnumValN(GenClangAttrPCHRead, "gen-clang-attr-pch-read",
++ "Generate clang PCH attribute reader"),
++ clEnumValN(GenClangAttrPCHWrite, "gen-clang-attr-pch-write",
++ "Generate clang PCH attribute writer"),
++ clEnumValN(GenClangAttrHasAttributeImpl,
++ "gen-clang-attr-has-attribute-impl",
++ "Generate a clang attribute spelling list"),
++ clEnumValN(GenClangAttrSpellingListIndex,
++ "gen-clang-attr-spelling-index",
++ "Generate a clang attribute spelling index"),
++ clEnumValN(GenClangAttrASTVisitor,
++ "gen-clang-attr-ast-visitor",
++ "Generate a recursive AST visitor for clang attributes"),
++ clEnumValN(GenClangAttrTemplateInstantiate,
++ "gen-clang-attr-template-instantiate",
++ "Generate a clang template instantiate code"),
++ clEnumValN(GenClangAttrParsedAttrList,
++ "gen-clang-attr-parsed-attr-list",
++ "Generate a clang parsed attribute list"),
++ clEnumValN(GenClangAttrParsedAttrImpl,
++ "gen-clang-attr-parsed-attr-impl",
++ "Generate the clang parsed attribute helpers"),
++ clEnumValN(GenClangAttrParsedAttrKinds,
++ "gen-clang-attr-parsed-attr-kinds",
++ "Generate a clang parsed attribute kinds"),
++ clEnumValN(GenClangAttrDump, "gen-clang-attr-dump",
++ "Generate clang attribute dumper"),
++ clEnumValN(GenClangDiagsDefs, "gen-clang-diags-defs",
++ "Generate Clang diagnostics definitions"),
++ clEnumValN(GenClangDiagGroups, "gen-clang-diag-groups",
++ "Generate Clang diagnostic groups"),
++ clEnumValN(GenClangDiagsIndexName, "gen-clang-diags-index-name",
++ "Generate Clang diagnostic name index"),
++ clEnumValN(GenClangCommentNodes, "gen-clang-comment-nodes",
++ "Generate Clang AST comment nodes"),
++ clEnumValN(GenClangDeclNodes, "gen-clang-decl-nodes",
++ "Generate Clang AST declaration nodes"),
++ clEnumValN(GenClangStmtNodes, "gen-clang-stmt-nodes",
++ "Generate Clang AST statement nodes"),
++ clEnumValN(GenClangSACheckers, "gen-clang-sa-checkers",
++ "Generate Clang Static Analyzer checkers"),
++ clEnumValN(GenClangCommentHTMLTags, "gen-clang-comment-html-tags",
++ "Generate efficient matchers for HTML tag "
++ "names that are used in documentation comments"),
++ clEnumValN(GenClangCommentHTMLTagsProperties,
++ "gen-clang-comment-html-tags-properties",
++ "Generate efficient matchers for HTML tag "
++ "properties"),
++ clEnumValN(GenClangCommentHTMLNamedCharacterReferences,
++ "gen-clang-comment-html-named-character-references",
++ "Generate function to translate named character "
++ "references to UTF-8 sequences"),
++ clEnumValN(GenClangCommentCommandInfo, "gen-clang-comment-command-info",
++ "Generate command properties for commands that "
++ "are used in documentation comments"),
++ clEnumValN(GenClangCommentCommandList, "gen-clang-comment-command-list",
++ "Generate list of commands that are used in "
++ "documentation comments"),
++ clEnumValN(GenArmNeon, "gen-arm-neon", "Generate arm_neon.h for clang"),
++ clEnumValN(GenArmNeonSema, "gen-arm-neon-sema",
++ "Generate ARM NEON sema support for clang"),
++ clEnumValN(GenArmNeonTest, "gen-arm-neon-test",
++ "Generate ARM NEON tests for clang"),
++ clEnumValN(GenAttrDocs, "gen-attr-docs",
++ "Generate attribute documentation"),
++ clEnumValEnd));
+
+-cl::opt<std::string>
++static cl::opt<std::string>
+ ClangComponent("clang-component",
+ cl::desc("Only use warnings from specified component"),
+ cl::value_desc("component"), cl::Hidden);
+
+ bool ClangTableGenMain(raw_ostream &OS, RecordKeeper &Records) {
+ switch (Action) {
+ case GenClangAttrClasses:
+ EmitClangAttrClass(Records, OS);
+ break;
+ case GenClangAttrParserStringSwitches:
+@@ -230,21 +228,20 @@
+ case GenArmNeonTest:
+ EmitNeonTest(Records, OS);
+ break;
+ case GenAttrDocs:
+ EmitClangAttrDocs(Records, OS);
+ break;
+ }
+
+ return false;
+ }
+-}
+
+ int main(int argc, char **argv) {
+ sys::PrintStackTraceOnErrorSignal();
+ PrettyStackTraceProgram X(argc, argv);
+ cl::ParseCommandLineOptions(argc, argv);
+
+ return TableGenMain(argv[0], &ClangTableGenMain);
+ }
+
+ #ifdef __has_feature
+--- lib/IR/LegacyPassManager.cpp 2015-01-28 09:39:35.000000000 -0800
++++ lib/IR/LegacyPassManager.cpp 2015-10-05 11:01:32.789436446 -0700
+@@ -40,15 +40,18 @@
+ // pass name to be printed before it executes.
+ //
+
+-namespace {
+ // Different debug levels that can be enabled...
+ enum PassDebugLevel {
+- Disabled, Arguments, Structure, Executions, Details
++ Disabled,
++ Arguments,
++ Structure,
++ Executions,
++ Details
+ };
+-}
+
+ static cl::opt<enum PassDebugLevel>
+-PassDebugging("debug-pass", cl::Hidden,
++PassDebugging("debug-pass",
++ cl::Hidden,
+ cl::desc("Print PassManager debugging information"),
+ cl::values(
+ clEnumVal(Disabled , "disable debug output"),
+@@ -58,36 +61,44 @@
+ clEnumVal(Details , "print pass details when it is executed"),
+ clEnumValEnd));
+
+-namespace {
+-typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
+-PassOptionList;
+-}
+-
+ // Print IR out before/after specified passes.
+-static PassOptionList
+-PrintBefore("print-before",
+- llvm::cl::desc("Print IR before specified passes"),
+- cl::Hidden);
+-
+-static PassOptionList
+-PrintAfter("print-after",
+- llvm::cl::desc("Print IR after specified passes"),
+- cl::Hidden);
++static llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
++PrintBefore(cl::Prefix, "print-before",
++ cl::desc("Print IR before specified passes"),
++ cl::value_desc("Print IR before specified passes"),
++ cl::Hidden,
++ cl::ZeroOrMore);
++
++static llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
++PrintAfter(cl::Prefix, "print-after",
++ cl::desc("Print IR after specified passes"),
++ cl::value_desc("Print IR after specified passes"),
++ cl::Hidden,
++ cl::ZeroOrMore);
+
+ static cl::opt<bool>
+-PrintBeforeAll("print-before-all",
++PrintBeforeAll(cl::NormalFormatting, "print-before-all",
+ llvm::cl::desc("Print IR before each pass"),
++ llvm::cl::value_desc("Print IR before each pass"),
++ cl::Hidden,
++ cl::Optional,
+ cl::init(false));
++
+ static cl::opt<bool>
+-PrintAfterAll("print-after-all",
++PrintAfterAll(cl::NormalFormatting, "print-after-all",
+ llvm::cl::desc("Print IR after each pass"),
++ llvm::cl::value_desc("Print IR after each pass"),
++ cl::Hidden,
++ cl::Optional,
+ cl::init(false));
+
+ /// This is a helper to determine whether to print IR before or
+ /// after a pass.
+
+-static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
+- PassOptionList &PassesToPrint) {
++static bool
++ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
++ llvm::cl::list<const llvm::PassInfo *, bool,
++ PassNameParser> &PassesToPrint) {
+ for (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
+ const llvm::PassInfo *PassInf = PassesToPrint[i];
+ if (PassInf)
+--- lib/Support/CommandLine.cpp 2015-01-13 11:14:20.000000000 -0800
++++ lib/Support/CommandLine.cpp 2016-01-19 10:13:33.212967353 -0800
+@@ -41,6 +41,8 @@
+
+ #define DEBUG_TYPE "commandline"
+
++#include <iostream>
++
+ //===----------------------------------------------------------------------===//
+ // Template instantiations and anchors.
+ //
+@@ -85,7 +87,7 @@
+
+ // Globals for name and overview of program. Program name is not a string to
+ // avoid static ctor/dtor issues.
+-static char ProgramName[80] = "<premain>";
++static std::string ProgramName("<premain>");
+ static const char *ProgramOverview = nullptr;
+
+ // This collects additional help to be printed.
+@@ -102,14 +104,14 @@
+
+ /// RegisteredOptionList - This is the list of the command line options that
+ /// have statically constructed themselves.
+-static Option *RegisteredOptionList = nullptr;
++Option *Option::RegisteredOptionList = nullptr;
+
+ void Option::addArgument() {
+ assert(!NextRegistered && "argument multiply registered!");
++ Option *O = dynamic_cast<Option*>(this);
++ assert(O && "Cannot dynamic_cast to correct type!");
+
+- NextRegistered = RegisteredOptionList;
+- RegisteredOptionList = this;
+- MarkOptionsChanged();
++ Option::registerOption(O);
+ }
+
+ void Option::removeArgument() {
+@@ -149,24 +151,26 @@
+
+ /// GetOptionInfo - Scan the list of registered options, turning them into data
+ /// structures that are easier to handle.
+-static void GetOptionInfo(SmallVectorImpl<Option *> &PositionalOpts,
+- SmallVectorImpl<Option *> &SinkOpts,
++static void GetOptionInfo(std::vector<Option *> &PositionalOpts,
++ std::vector<Option *> &SinkOpts,
+ StringMap<Option *> &OptionsMap) {
+ bool HadErrors = false;
+- SmallVector<const char *, 16> OptionNames;
++ std::vector<const char *> OptionNames;
+ Option *CAOpt = nullptr; // The ConsumeAfter option if it exists.
+- for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
++ for (Option *O = Option::getRegisteredOptionList(); O;
++ O = O->getNextRegisteredOption()) {
+ // If this option wants to handle multiple option names, get the full set.
+ // This handles enum options like "-O1 -O2" etc.
+ O->getExtraOptionNames(OptionNames);
+- if (O->ArgStr[0])
++
++ if (O->ArgStr && *O->ArgStr)
+ OptionNames.push_back(O->ArgStr);
+
+ // Handle named options.
+ for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
+ // Add argument to the argument map!
+ if (!OptionsMap.insert(std::make_pair(OptionNames[i], O)).second) {
+- errs() << ProgramName << ": CommandLine Error: Option '"
++ errs() << ProgramName.c_str() << ": CommandLine Error: Option '"
+ << OptionNames[i] << "' registered more than once!\n";
+ HadErrors = true;
+ }
+@@ -201,6 +205,24 @@
+ report_fatal_error("inconsistency in registered CommandLine options");
+ }
+
++/// HandleSpecialPrefixOptions - certain options need special handling
++/// of their Argyment/Value pair, because there will be no space separator
++/// between the two. For example -O<N> (optimization level).
++static void HandleSpecialPrefixOptions(StringRef &ArgName, StringRef &Value) {
++ if (ArgName.empty())
++ return;
++
++ char AN = ArgName.front();
++ switch (AN) {
++ default:
++ break;
++ case 'O':
++ Value = ArgName.substr(1, 1);
++ ArgName = ArgName.substr(0, 1);
++ break;
++ }
++}
++
+ /// LookupOption - Lookup the option specified by the specified option on the
+ /// command line. If there is a value specified (after an equal sign) return
+ /// that as well. This assumes that leading dashes have already been stripped.
+@@ -210,12 +232,35 @@
+ if (Arg.empty())
+ return nullptr;
+
++ HandleSpecialPrefixOptions(Arg, Value);
++
+ size_t EqualPos = Arg.find('=');
+
+ // If we have an equals sign, remember the value.
+ if (EqualPos == StringRef::npos) {
++ StringRef InputFile;
++
+ // Look up the option.
+ StringMap<Option *>::const_iterator I = OptionsMap.find(Arg);
++
++ // TableGen
++ if (I == OptionsMap.end()) {
++ InputFile = "<input file>";
++ I = OptionsMap.find(InputFile);
++ }
++
++ // lli && llc
++ if (I == OptionsMap.end()) {
++ InputFile = "<input bitcode>";
++ I = OptionsMap.find(InputFile);
++ }
++
++ // opt
++ if (I == OptionsMap.end()) {
++ InputFile = "<input bitcode file>";
++ I = OptionsMap.find(InputFile);
++ }
++
+ return I != OptionsMap.end() ? I->second : nullptr;
+ }
+
+@@ -254,7 +299,7 @@
+ ie = OptionsMap.end();
+ it != ie; ++it) {
+ Option *O = it->second;
+- SmallVector<const char *, 16> OptionNames;
++ std::vector<const char *> OptionNames;
+ O->getExtraOptionNames(OptionNames);
+ if (O->ArgStr[0])
+ OptionNames.push_back(O->ArgStr);
+@@ -322,9 +367,11 @@
+ // Enforce value requirements
+ switch (Handler->getValueExpectedFlag()) {
+ case ValueRequired:
+- if (!Value.data()) { // No value specified?
++ if (Value.empty()) { // No value specified?
+ if (i + 1 >= argc)
+- return Handler->error("requires a value!");
++ return
++ Handler->error("argument requires a value but none was provided!");
++
+ // Steal the next argument, like for '-o filename'
+ assert(argv && "null check");
+ Value = argv[++i];
+@@ -335,11 +382,17 @@
+ return Handler->error("multi-valued option specified"
+ " with ValueDisallowed modifier!");
+
+- if (Value.data())
++ if (!Value.empty())
+ return Handler->error("does not allow a value! '" + Twine(Value) +
+ "' specified.");
+ break;
+ case ValueOptional:
++ case ValuePositionalNoArgs:
++ break;
++ case ValuePositionalWithArgs:
++ break;
++ default:
++ return Handler->error("Unknown/invalid Option type!");
+ break;
+ }
+
+@@ -373,7 +426,15 @@
+
+ static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
+ int Dummy = i;
+- return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
++ bool R = ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
++ return R;
++}
++
++static bool ProvidePositionalOptionWithArgs(Option *Handler, StringRef Arg,
++ int i, unsigned &ValNo,
++ unsigned &NumPositionsRequired) {
++ // FIXME: IMPLEMENT
++ return false;
+ }
+
+ // Option predicates...
+@@ -416,7 +477,7 @@
+ /// see if this is a prefix or grouped option. If so, split arg into output an
+ /// Arg/Value pair and return the Option to parse it with.
+ static Option *
+-HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
++HandlePrefixedOrGroupedOption(std::string &Arg, std::string &Value,
+ bool &ErrorParsing,
+ const StringMap<Option *> &OptionsMap) {
+ if (Arg.size() == 1)
+@@ -465,7 +526,10 @@
+
+ static bool RequiresValue(const Option *O) {
+ return O->getNumOccurrencesFlag() == cl::Required ||
+- O->getNumOccurrencesFlag() == cl::OneOrMore;
++ O->getNumOccurrencesFlag() == cl::OneOrMore ||
++ O->getValueExpectedFlag() == cl::ValueRequired ||
++ O->getValueExpectedFlag() == cl::ValuePositionalNoArgs ||
++ O->getValueExpectedFlag() == cl::ValuePositionalWithArgs;
+ }
+
+ static bool EatsUnboundedNumberOfValues(const Option *O) {
+@@ -480,9 +544,9 @@
+ static bool isGNUSpecial(char C) { return strchr("\\\"\' ", C); }
+
+ void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
+- SmallVectorImpl<const char *> &NewArgv,
++ std::vector<const char *> &NewArgv,
+ bool MarkEOLs) {
+- SmallString<128> Token;
++ SmallString<PATH_MAX> Token;
+ for (size_t I = 0, E = Src.size(); I != E; ++I) {
+ // Consume runs of whitespace.
+ if (Token.empty()) {
+@@ -556,7 +620,7 @@
+ /// consumed in this case.
+ ///
+ /// * Otherwise, backslashes are interpreted literally.
+-static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
++static size_t parseBackslash(StringRef Src, size_t I, SmallString<256> &Token) {
+ size_t E = Src.size();
+ int BackslashCount = 0;
+ // Skip the backslashes.
+@@ -578,9 +642,9 @@
+ }
+
+ void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
+- SmallVectorImpl<const char *> &NewArgv,
++ std::vector<const char *> &NewArgv,
+ bool MarkEOLs) {
+- SmallString<128> Token;
++ SmallString<256> Token;
+
+ // This is a small state machine to consume characters until it reaches the
+ // end of the source string.
+@@ -657,7 +721,7 @@
+
+ static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
+ TokenizerCallback Tokenizer,
+- SmallVectorImpl<const char *> &NewArgv,
++ std::vector<const char *> &NewArgv,
+ bool MarkEOLs = false) {
+ ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
+ MemoryBuffer::getFile(FName);
+@@ -684,7 +748,7 @@
+ /// \brief Expand response files on a command line recursively using the given
+ /// StringSaver and tokenization strategy.
+ bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
+- SmallVectorImpl<const char *> &Argv,
++ std::vector<const char *> &Argv,
+ bool MarkEOLs) {
+ unsigned RspFiles = 0;
+ bool AllExpanded = true;
+@@ -711,7 +775,7 @@
+ // contents. Nested response files are expanded in subsequent iterations.
+ // FIXME: If a nested response file uses a relative path, is it relative to
+ // the cwd of the process or the response file?
+- SmallVector<const char *, 0> ExpandedArgv;
++ std::vector<const char *> ExpandedArgv;
+ if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
+ MarkEOLs)) {
+ // We couldn't read this file, so we leave it in the argument stream and
+@@ -764,7 +828,7 @@
+
+ // Get program's "name", which we wouldn't know without the caller
+ // telling us.
+- SmallVector<const char *, 20> newArgv;
++ std::vector<const char *> newArgv;
+ StrDupSaver Saver;
+ newArgv.push_back(Saver.SaveString(progName));
+
+@@ -778,27 +842,25 @@
+ void cl::ParseCommandLineOptions(int argc, const char *const *argv,
+ const char *Overview) {
+ // Process all registered options.
+- SmallVector<Option *, 4> PositionalOpts;
+- SmallVector<Option *, 4> SinkOpts;
++ std::vector<Option*> PositionalOpts;
++ std::vector<Option*> SinkOpts;
+ StringMap<Option *> Opts;
+ GetOptionInfo(PositionalOpts, SinkOpts, Opts);
+
+ assert((!Opts.empty() || !PositionalOpts.empty()) && "No options specified!");
+
+ // Expand response files.
+- SmallVector<const char *, 20> newArgv;
++ std::vector<const char*> newArgv;
++
+ for (int i = 0; i != argc; ++i)
+ newArgv.push_back(argv[i]);
++
+ StrDupSaver Saver;
+ ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
+ argv = &newArgv[0];
+ argc = static_cast<int>(newArgv.size());
+
+- // Copy the program name into ProgName, making sure not to overflow it.
+- StringRef ProgName = sys::path::filename(argv[0]);
+- size_t Len = std::min(ProgName.size(), size_t(79));
+- memcpy(ProgramName, ProgName.data(), Len);
+- ProgramName[Len] = '\0';
++ ProgramName = sys::path::filename(argv[0]).str();
+
+ ProgramOverview = Overview;
+ bool ErrorParsing = false;
+@@ -810,6 +872,7 @@
+ bool HasUnlimitedPositionals = false;
+
+ Option *ConsumeAfterOpt = nullptr;
++
+ if (!PositionalOpts.empty()) {
+ if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
+ assert(PositionalOpts.size() > 1 &&
+@@ -819,8 +882,7 @@
+
+ // Calculate how many positional values are _required_.
+ bool UnboundedFound = false;
+- for (size_t i = ConsumeAfterOpt ? 1 : 0, e = PositionalOpts.size(); i != e;
+- ++i) {
++ for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
+ Option *Opt = PositionalOpts[i];
+ if (RequiresValue(Opt))
+ ++NumPositionalRequired;
+@@ -844,13 +906,14 @@
+ }
+ UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
+ }
++
+ HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
+ }
+
+ // PositionalVals - A vector of "positional" arguments we accumulate into
+ // the process at the end.
+ //
+- SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
++ std::vector<std::pair<StringRef, unsigned> > PositionalVals;
+
+ // If the program has named positional arguments, and the name has been run
+ // across, keep track of which positional argument was named. Otherwise put
+@@ -862,39 +925,25 @@
+ for (int i = 1; i < argc; ++i) {
+ Option *Handler = nullptr;
+ Option *NearestHandler = nullptr;
++ Option *PrefixOrGroupHandler = nullptr;
+ std::string NearestHandlerString;
+- StringRef Value;
++ StringRef Value = "";
+ StringRef ArgName = "";
+
+- // If the option list changed, this means that some command line
+- // option has just been registered or deregistered. This can occur in
+- // response to things like -load, etc. If this happens, rescan the options.
+- if (OptionListChanged) {
+- PositionalOpts.clear();
+- SinkOpts.clear();
+- Opts.clear();
+- GetOptionInfo(PositionalOpts, SinkOpts, Opts);
+- OptionListChanged = false;
+- }
+-
+ // Check to see if this is a positional argument. This argument is
+ // considered to be positional if it doesn't start with '-', if it is "-"
+ // itself, or if we have seen "--" already.
+ //
+- if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
+- // Positional argument!
+- if (ActivePositionalArg) {
+- ProvidePositionalOption(ActivePositionalArg, argv[i], i);
+- continue; // We are done!
+- }
+-
++ if (((argv[i][0] != '-') && (argv[i][1] != '\0')) ||
++ ((argv[i][0] == '-') && (argv[i][1] == '\0')) || DashDashFound) {
+ if (!PositionalOpts.empty()) {
+ PositionalVals.push_back(std::make_pair(argv[i], i));
+
+ // All of the positional arguments have been fulfulled, give the rest to
+ // the consume after option... if it's specified...
+ //
+- if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
++ if ((PositionalVals.size() >= NumPositionalRequired) &&
++ ConsumeAfterOpt) {
+ for (++i; i < argc; ++i)
+ PositionalVals.push_back(std::make_pair(argv[i], i));
+ break; // Handle outside of the argument processing loop...
+@@ -913,6 +962,7 @@
+ // option is another positional argument. If so, treat it as an argument,
+ // otherwise feed it to the eating positional.
+ ArgName = argv[i] + 1;
++
+ // Eat leading dashes.
+ while (!ArgName.empty() && ArgName[0] == '-')
+ ArgName = ArgName.substr(1);
+@@ -924,17 +974,32 @@
+ }
+
+ } else { // We start with a '-', must be an argument.
+- ArgName = argv[i] + 1;
++ // ArgName = i == (argc - 1) ? argv[i] : argv[i] + 1;
++ ArgName = argv[i];
++
+ // Eat leading dashes.
+ while (!ArgName.empty() && ArgName[0] == '-')
+ ArgName = ArgName.substr(1);
+
+ Handler = LookupOption(ArgName, Value, Opts);
+-
+- // Check to see if this "option" is really a prefixed or grouped argument.
+- if (!Handler)
+- Handler =
+- HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing, Opts);
++ if (Handler) {
++ enum FormattingFlags FF = Handler->getFormattingFlag();
++ if ((FF == llvm::cl::Prefix) || (FF == llvm::cl::Grouping)) {
++ if (Value.empty())
++ Value = argv[++i];
++
++ std::string SA = ArgName.str();
++ std::string SV = Value.str();
++ SA.append(SV);
++
++ // Check to see if this "option" is really a prefixed or
++ // grouped argument.
++ PrefixOrGroupHandler =
++ HandlePrefixedOrGroupedOption(SA, SV, ErrorParsing, Opts);
++ if (PrefixOrGroupHandler)
++ Handler = PrefixOrGroupHandler;
++ }
++ }
+
+ // Otherwise, look for the closest available option to report to the user
+ // in the upcoming error.
+@@ -945,22 +1010,23 @@
+
+ if (!Handler) {
+ if (SinkOpts.empty()) {
+- errs() << ProgramName << ": Unknown command line argument '" << argv[i]
+- << "'. Try: '" << argv[0] << " -help'\n";
++ errs() << ProgramName.c_str()
++ << ": Unknown command line argument '" << argv[i]
++ << "'. Try: '" << argv[0] << " -help'\n";
+
+ if (NearestHandler) {
+ // If we know a near match, report it as well.
+- errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
+- << "'?\n";
++ errs() << ProgramName.c_str()
++ << ": Did you mean '-" << NearestHandlerString << "'?\n";
+ }
+
+ ErrorParsing = true;
+ } else {
+- for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
+- E = SinkOpts.end();
+- I != E; ++I)
++ for (std::vector<Option *>::iterator I = SinkOpts.begin(),
++ E = SinkOpts.end(); I != E; ++I)
+ (*I)->addOccurrence(i, "", argv[i]);
+ }
++
+ continue;
+ }
+
+@@ -974,50 +1040,77 @@
+
+ // Check and handle positional arguments now...
+ if (NumPositionalRequired > PositionalVals.size()) {
+- errs() << ProgramName
+- << ": Not enough positional command line arguments specified!\n"
+- << "Must specify at least " << NumPositionalRequired
+- << " positional arguments: See: " << argv[0] << " -help\n";
++ errs() << ProgramName.c_str()
++ << ": Not enough positional command line arguments specified!\n"
++ << "Must specify at least " << NumPositionalRequired
++ << " positional arguments: See: " << argv[0] << " -help\n";
+
+ ErrorParsing = true;
+ } else if (!HasUnlimitedPositionals &&
+ PositionalVals.size() > PositionalOpts.size()) {
+- errs() << ProgramName << ": Too many positional arguments specified!\n"
+- << "Can specify at most " << PositionalOpts.size()
+- << " positional arguments: See: " << argv[0] << " -help\n";
++ errs() << ProgramName.c_str()
++ << ": Too many positional arguments specified!\n"
++ << "Can specify at most " << PositionalOpts.size()
++ << " positional arguments: See: " << argv[0] << " -help\n";
+ ErrorParsing = true;
+
+ } else if (!ConsumeAfterOpt) {
+ // Positional args have already been handled if ConsumeAfter is specified.
+- unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
++ unsigned ValNo = 0;
++ unsigned NumVals = static_cast<unsigned>(PositionalVals.size());
+ for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
+- if (RequiresValue(PositionalOpts[i])) {
+- ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
++ Option *PO = PositionalOpts[i];
++ if (RequiresValue(PO)) {
++ ProvidePositionalOption(PO, PositionalVals[ValNo].first,
+ PositionalVals[ValNo].second);
+ ValNo++;
+ --NumPositionalRequired; // We fulfilled our duty...
+ }
+
++ enum llvm::cl::ValueExpected VE = PO->getValueExpectedFlag();
++
++ // If it's a positional argument, provide it.
++ if ((NumVals - ValNo) > NumPositionalRequired) {
++ if (VE == llvm::cl::ValuePositionalNoArgs) {
++ ProvidePositionalOption(PO, PositionalVals[ValNo].first,
++ PositionalVals[ValNo].second);
++ ++ValNo;
++ --NumPositionalRequired;
++ continue;
++ } else if (VE == llvm::cl::ValuePositionalWithArgs) {
++ ProvidePositionalOptionWithArgs(PO, PositionalVals[ValNo].first,
++ PositionalVals[ValNo].second,
++ ValNo,
++ NumPositionalRequired);
++ continue;
++ }
++ }
++
+ // If we _can_ give this option more arguments, do so now, as long as we
+ // do not give it values that others need. 'Done' controls whether the
+ // option even _WANTS_ any more.
+ //
+- bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
+- while (NumVals - ValNo > NumPositionalRequired && !Done) {
+- switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
++ bool Done =
++ ((PO->getNumOccurrencesFlag() == cl::Required) &&
++ (VE != llvm::cl::ValuePositionalNoArgs));
++
++ while (((NumVals - ValNo) > NumPositionalRequired) && !Done) {
++ switch (PO->getNumOccurrencesFlag()) {
+ case cl::Optional:
+ Done = true; // Optional arguments want _at most_ one value
+ // FALL THROUGH
++ break;
+ case cl::ZeroOrMore: // Zero or more will take all they can get...
+ case cl::OneOrMore: // One or more will take all they can get...
+- ProvidePositionalOption(PositionalOpts[i],
+- PositionalVals[ValNo].first,
++ ProvidePositionalOption(PO, PositionalVals[ValNo].first,
+ PositionalVals[ValNo].second);
+ ValNo++;
+ break;
+ default:
+- llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
+- "positional argument processing!");
++ assert(0 && "Internal Compiler Error: "
++ "unexpected NumOccurrences flag "
++ "in positional argument processing!");
++ break;
+ }
+ }
+ }
+@@ -1029,7 +1122,7 @@
+ ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
+ PositionalVals[ValNo].first,
+ PositionalVals[ValNo].second);
+- ValNo++;
++ ++ValNo;
+ }
+
+ // Handle the case where there is just one positional option, and it's
+@@ -1041,7 +1134,7 @@
+ ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
+ PositionalVals[ValNo].first,
+ PositionalVals[ValNo].second);
+- ValNo++;
++ ++ValNo;
+ }
+
+ // Handle over all of the rest of the arguments to the
+@@ -1061,7 +1154,7 @@
+ Opt.second->error("must be specified at least once!");
+ ErrorParsing = true;
+ }
+- // Fall through
++ break;
+ default:
+ break;
+ }
+@@ -1095,7 +1188,7 @@
+ if (ArgName.empty())
+ errs() << HelpStr; // Be nice for positional arguments
+ else
+- errs() << ProgramName << ": for the -" << ArgName;
++ errs() << ProgramName.c_str() << ": for the -" << ArgName;
+
+ errs() << " option: " << Message << "\n";
+ return true;
+@@ -1106,7 +1199,9 @@
+ if (!MultiArg)
+ NumOccurrences++; // Increment the number of times we have been seen
+
+- switch (getNumOccurrencesFlag()) {
++ llvm::cl::NumOccurrencesFlag NOF = getNumOccurrencesFlag();
++
++ switch (NOF) {
+ case Optional:
+ if (NumOccurrences > 1)
+ return error("may only occur zero or one times!", ArgName);
+@@ -1121,7 +1216,11 @@
+ break;
+ }
+
+- return handleOccurrence(pos, ArgName, Value);
++ std::string SAN = ArgName;
++ std::string SV = Value;
++
++ bool R = handleOccurrence(pos, SAN.c_str(), SV.c_str());
++ return R;
+ }
+
+ // getValueStr - Get the value description string, using "DefaultMsg" if nothing
+@@ -1402,11 +1501,12 @@
+ PRINT_OPT_DIFF(float)
+ PRINT_OPT_DIFF(char)
+
+-void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
++void parser<std::string>::printOptionDiff(const Option &O,
++ const std::string &V,
+ OptionValue<std::string> D,
+ size_t GlobalWidth) const {
+ printOptionName(O, GlobalWidth);
+- outs() << "= " << V;
++ outs() << "= " << V.c_str();
+ size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
+ outs().indent(NumSpaces) << " (default: ";
+ if (D.hasValue())
+@@ -1427,20 +1527,22 @@
+ // -help and -help-hidden option implementation
+ //
+
+-static int OptNameCompare(const void *LHS, const void *RHS) {
+- typedef std::pair<const char *, Option *> pair_ty;
+-
+- return strcmp(((const pair_ty *)LHS)->first, ((const pair_ty *)RHS)->first);
+-}
++template<typename Ty>
++struct OptNameCompare : public std::binary_function<Ty, Ty, bool> {
++ inline bool operator()(const Ty& LHS, const Ty& RHS) const {
++ return std::strcmp(LHS.first, RHS.first) <= 0;
++ }
++};
+
+ // Copy Options into a vector so we can sort them as we like.
+ static void sortOpts(StringMap<Option *> &OptMap,
+- SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
++ std::vector<std::pair<const char*, Option*> > &Opts,
+ bool ShowHidden) {
+ SmallPtrSet<Option *, 128> OptionSet; // Duplicate option detection.
+
+ for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
+ I != E; ++I) {
++
+ // Ignore really-hidden options.
+ if (I->second->getOptionHiddenFlag() == ReallyHidden)
+ continue;
+@@ -1453,12 +1555,13 @@
+ if (!OptionSet.insert(I->second).second)
+ continue;
+
+- Opts.push_back(
+- std::pair<const char *, Option *>(I->getKey().data(), I->second));
++ std::pair<const char*, Option*> KVP(I->getKey().data(), I->second);
++ Opts.push_back(KVP);
+ }
+
+ // Sort the options list alphabetically.
+- qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
++ OptNameCompare<std::pair<const char*, Option*> > ONC;
++ std::sort(Opts.begin(), Opts.end(), ONC);
+ }
+
+ namespace {
+@@ -1466,8 +1569,9 @@
+ class HelpPrinter {
+ protected:
+ const bool ShowHidden;
+- typedef SmallVector<std::pair<const char *, Option *>, 128>
++ typedef std::vector<std::pair<const char *, Option *> >
+ StrOptionPairVector;
++
+ // Print the options. Opts is assumed to be alphabetically sorted.
+ virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
+ for (size_t i = 0, e = Opts.size(); i != e; ++i)
+@@ -1484,8 +1588,8 @@
+ return;
+
+ // Get all the options.
+- SmallVector<Option *, 4> PositionalOpts;
+- SmallVector<Option *, 4> SinkOpts;
++ std::vector<Option *> PositionalOpts;
++ std::vector<Option *> SinkOpts;
+ StringMap<Option *> OptMap;
+ GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
+
+@@ -1495,7 +1599,7 @@
+ if (ProgramOverview)
+ outs() << "OVERVIEW: " << ProgramOverview << "\n";
+
+- outs() << "USAGE: " << ProgramName << " [options]";
++ outs() << "USAGE: " << ProgramName.c_str() << " [options]";
+
+ // Print out the positional options.
+ Option *CAOpt = nullptr; // The cl::ConsumeAfter option, if it exists...
+@@ -1710,12 +1814,12 @@
+ return;
+
+ // Get all the options.
+- SmallVector<Option *, 4> PositionalOpts;
+- SmallVector<Option *, 4> SinkOpts;
++ std::vector<Option *> PositionalOpts;
++ std::vector<Option *> SinkOpts;
+ StringMap<Option *> OptMap;
+ GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
+
+- SmallVector<std::pair<const char *, Option *>, 128> Opts;
++ std::vector<std::pair<const char *, Option *> > Opts;
+ sortOpts(OptMap, Opts, /*ShowHidden*/ true);
+
+ // Compute the maximum argument length...
+@@ -1825,8 +1929,8 @@
+
+ void cl::getRegisteredOptions(StringMap<Option *> &Map) {
+ // Get all the options.
+- SmallVector<Option *, 4> PositionalOpts; // NOT USED
+- SmallVector<Option *, 4> SinkOpts; // NOT USED
++ std::vector<Option *> PositionalOpts; // NOT USED
++ std::vector<Option *> SinkOpts; // NOT USED
+ assert(Map.size() == 0 && "StringMap must be empty");
+ GetOptionInfo(PositionalOpts, SinkOpts, Map);
+ return;
+--- lib/Support/PluginLoader.cpp 2012-12-03 08:50:05.000000000 -0800
++++ lib/Support/PluginLoader.cpp 2016-01-24 11:02:33.000000000 -0800
+@@ -34,6 +34,21 @@
+ }
+ }
+
++bool PluginLoader::operator==(const std::string &Filename) const {
++ sys::SmartScopedLock<true> Lock(*PluginsLock);
++ for (std::vector<std::string>::const_iterator I = Plugins->begin(),
++ E = Plugins->end(); I != E; ++I) {
++ if (*I == Filename)
++ return true;
++ }
++
++ return false;
++}
++
++bool PluginLoader::operator!=(const std::string &Filename) const {
++ return !this->operator==(Filename);
++}
++
+ unsigned PluginLoader::getNumPlugins() {
+ sys::SmartScopedLock<true> Lock(*PluginsLock);
+ return Plugins.isConstructed() ? Plugins->size() : 0;
+--- include/llvm/Support/CommandLine.h 2015-01-13 11:14:20.000000000 -0800
++++ include/llvm/Support/CommandLine.h 2016-01-19 11:56:32.087336770 -0800
+@@ -24,6 +24,7 @@
+ #include "llvm/ADT/StringMap.h"
+ #include "llvm/ADT/Twine.h"
+ #include "llvm/Support/Compiler.h"
++#include "llvm/Support/raw_ostream.h"
+ #include <cassert>
+ #include <climits>
+ #include <cstdarg>
+@@ -97,9 +98,11 @@
+
+ enum ValueExpected { // Is a value required for the option?
+ // zero reserved for the unspecified value
+- ValueOptional = 0x01, // The value can appear... or not
+- ValueRequired = 0x02, // The value is required to appear!
+- ValueDisallowed = 0x03 // A value may not be specified (for flags)
++ ValueOptional = 0x01, // The value can appear... or not
++ ValueRequired = 0x02, // The value is required to appear!
++ ValueDisallowed = 0x03, // A value may not be specified (for flags)
++ ValuePositionalNoArgs = 0x04, // Positional Argument, no additional args
++ ValuePositionalWithArgs = 0x05 // Positional Argument, with additional args
+ };
+
+ enum OptionHidden { // Control whether -help shows this option
+@@ -137,6 +140,36 @@
+ };
+
+ //===----------------------------------------------------------------------===//
++// Generic Filename Locations
++//
++struct GenericFilenameLocation {
++ GenericFilenameLocation() : Value("") { }
++ GenericFilenameLocation(const std::string &S) : Value(S) { }
++
++ void operator=(const std::string &S) {
++ if (!S.empty())
++ Value = S;
++ }
++
++ std::string Value;
++};
++
++struct GenericFilenameLocations {
++ GenericFilenameLocations() : Value() { }
++ GenericFilenameLocations(const std::string &S)
++ : Value() {
++ Value.push_back(S);
++ }
++
++ void operator=(const std::string &S) {
++ if (!S.empty())
++ Value.push_back(S);
++ }
++
++ std::vector<std::string> Value;
++};
++
++//===----------------------------------------------------------------------===//
+ // Option Category class
+ //
+ class OptionCategory {
+@@ -162,9 +195,15 @@
+ // Option Base class
+ //
+ class alias;
++
+ class Option {
+ friend class alias;
+
++protected:
++ /// RegisteredOptionList - This is the list of the command line options
++ /// that have statically constructed themselves.
++ static Option *RegisteredOptionList;
++
+ // handleOccurrences - Overriden by subclasses to handle the value passed into
+ // an argument. Should return true if there was an error processing the
+ // argument and the program should exit.
+@@ -182,13 +221,13 @@
+ int NumOccurrences; // The number of times specified
+ // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid
+ // problems with signed enums in bitfields.
+- unsigned Occurrences : 3; // enum NumOccurrencesFlag
++ unsigned Occurrences; // enum NumOccurrencesFlag
+ // not using the enum type for 'Value' because zero is an implementation
+ // detail representing the non-value
+- unsigned Value : 2;
+- unsigned HiddenFlag : 2; // enum OptionHidden
+- unsigned Formatting : 2; // enum FormattingFlags
+- unsigned Misc : 3;
++ unsigned Value;
++ unsigned HiddenFlag; // enum OptionHidden
++ unsigned Formatting; // enum FormattingFlags
++ unsigned Misc;
+ unsigned Position; // Position of last occurrence of the option
+ unsigned AdditionalVals; // Greater than 0 for multi-valued option.
+ Option *NextRegistered; // Singly linked list of registered options.
+@@ -200,23 +239,28 @@
+ OptionCategory *Category; // The Category this option belongs to
+
+ inline enum NumOccurrencesFlag getNumOccurrencesFlag() const {
+- return (enum NumOccurrencesFlag)Occurrences;
++ return static_cast<enum NumOccurrencesFlag>(Occurrences);
+ }
++
+ inline enum ValueExpected getValueExpectedFlag() const {
+- return Value ? ((enum ValueExpected)Value) : getValueExpectedFlagDefault();
++ return Value ? static_cast<enum ValueExpected>(Value) :
++ static_cast<enum ValueExpected>(getValueExpectedFlagDefault());
+ }
++
+ inline enum OptionHidden getOptionHiddenFlag() const {
+- return (enum OptionHidden)HiddenFlag;
++ return static_cast<enum OptionHidden>(HiddenFlag);
+ }
++
+ inline enum FormattingFlags getFormattingFlag() const {
+- return (enum FormattingFlags)Formatting;
++ return static_cast<enum FormattingFlags>(Formatting);
+ }
++
+ inline unsigned getMiscFlags() const { return Misc; }
+ inline unsigned getPosition() const { return Position; }
+ inline unsigned getNumAdditionalVals() const { return AdditionalVals; }
+
+ // hasArgStr - Return true if the argstr != ""
+- bool hasArgStr() const { return ArgStr[0] != 0; }
++ bool hasArgStr() const { return ArgStr && *ArgStr != '\0'; }
+
+ //-------------------------------------------------------------------------===
+ // Accessor functions set by OptionModifiers
+@@ -233,16 +277,78 @@
+ void setCategory(OptionCategory &C) { Category = &C; }
+
+ protected:
++ Option() : NumOccurrences(0), Occurrences(0), Value(0), HiddenFlag(0),
++ Formatting(0), Misc(0), Position(0), AdditionalVals(0),
++ NextRegistered(0), ArgStr(""), HelpStr(""), ValueStr(""),
++ Category(0) { }
+ explicit Option(enum NumOccurrencesFlag OccurrencesFlag,
+ enum OptionHidden Hidden)
+- : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
+- HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0), Position(0),
+- AdditionalVals(0), NextRegistered(nullptr), ArgStr(""), HelpStr(""),
+- ValueStr(""), Category(&GeneralCategory) {}
++ : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
++ HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0), Position(0),
++ AdditionalVals(0), NextRegistered(nullptr), ArgStr(""), HelpStr(""),
++ ValueStr(""), Category(&GeneralCategory) {}
+
+ inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; }
+
+ public:
++ Option(const Option &RHS)
++ : NumOccurrences(RHS.NumOccurrences), Occurrences(RHS.Occurrences),
++ Value(RHS.Value), HiddenFlag(RHS.HiddenFlag),
++ Formatting(RHS.Formatting), Misc(RHS.Misc),
++ Position(RHS.Position), AdditionalVals(RHS.AdditionalVals),
++ NextRegistered(RHS.NextRegistered), ArgStr(RHS.ArgStr),
++ HelpStr(RHS.HelpStr), ValueStr(RHS.ValueStr),
++ Category(RHS.Category) { }
++
++ Option(Option &&RHS)
++ : NumOccurrences(RHS.NumOccurrences), Occurrences(RHS.Occurrences),
++ Value(RHS.Value), HiddenFlag(RHS.HiddenFlag),
++ Formatting(RHS.Formatting), Misc(RHS.Misc),
++ Position(RHS.Position), AdditionalVals(RHS.AdditionalVals),
++ NextRegistered(RHS.NextRegistered), ArgStr(RHS.ArgStr),
++ HelpStr(RHS.HelpStr), ValueStr(RHS.ValueStr),
++ Category(RHS.Category) { }
++
++ Option &operator=(const Option &RHS) {
++ if (this != &RHS) {
++ NumOccurrences = RHS.NumOccurrences;
++ Occurrences = RHS.Occurrences;
++ Value = RHS.Value;
++ HiddenFlag = RHS.HiddenFlag;
++ Formatting = RHS.Formatting;
++ Misc = RHS.Misc;
++ Position = RHS.Position;
++ AdditionalVals = RHS.AdditionalVals;
++ NextRegistered = RHS.NextRegistered;
++ ArgStr = RHS.ArgStr;
++ HelpStr = RHS.HelpStr;
++ ValueStr = RHS.ValueStr;
++ Category = RHS.Category;
++ }
++
++ return *this;
++ }
++
++ const Option &operator=(Option &&RHS) {
++ if (this != &RHS) {
++ NumOccurrences = RHS.NumOccurrences;
++ Occurrences = RHS.Occurrences;
++ Value = RHS.Value;
++ HiddenFlag = RHS.HiddenFlag;
++ Formatting = RHS.Formatting;
++ Misc = RHS.Misc;
++ Position = RHS.Position;
++ AdditionalVals = RHS.AdditionalVals;
++ NextRegistered = RHS.NextRegistered;
++ ArgStr = RHS.ArgStr;
++ HelpStr = RHS.HelpStr;
++ ValueStr = RHS.ValueStr;
++ Category = RHS.Category;
++ }
++
++ return *this;
++ }
++
+ // addArgument - Register this argument with the commandline system.
+ //
+ void addArgument();
+@@ -253,8 +359,20 @@
+ /// For testing purposes only.
+ void removeArgument();
+
++ static void registerOption(Option *O) {
++ assert(O && "Invalid argument!");
++
++ O->NextRegistered = RegisteredOptionList;
++ RegisteredOptionList = O;
++ MarkOptionsChanged();
++ }
++
+ Option *getNextRegisteredOption() const { return NextRegistered; }
+
++ static Option *getRegisteredOptionList() {
++ return Option::RegisteredOptionList;
++ }
++
+ // Return the width of the option tag for printing...
+ virtual size_t getOptionWidth() const = 0;
+
+@@ -265,7 +383,7 @@
+
+ virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0;
+
+- virtual void getExtraOptionNames(SmallVectorImpl<const char *> &) {}
++ virtual void getExtraOptionNames(std::vector<const char*> &V) { }
+
+ // addOccurrence - Wrapper around handleOccurrence that enforces Flags.
+ //
+@@ -277,7 +395,7 @@
+
+ public:
+ inline int getNumOccurrences() const { return NumOccurrences; }
+- virtual ~Option() {}
++ virtual ~Option() { }
+ };
+
+ //===----------------------------------------------------------------------===//
+@@ -304,29 +422,39 @@
+ // the default constructor for the argument type does not give you what you
+ // want. This is only valid on "opt" arguments, not on "list" arguments.
+ //
+-template <class Ty> struct initializer {
++template <typename Ty> struct initializer {
+ const Ty &Init;
+- initializer(const Ty &Val) : Init(Val) {}
+
+- template <class Opt> void apply(Opt &O) const { O.setInitialValue(Init); }
++ initializer(const Ty &Val) : Init(Val) { }
++ initializer(const initializer &RHS) : Init(RHS.Init) { }
++ initializer(initializer &&RHS) : Init(RHS.Init) { }
++
++ template <typename Opt>
++ void apply(Opt &O) const { O.setInitialValue(Init); }
+ };
+
+-template <class Ty> initializer<Ty> init(const Ty &Val) {
+- return initializer<Ty>(Val);
++template<typename Ty>
++initializer<Ty> init(const Ty &Val) {
++ llvm::cl::initializer<Ty> I(Val);
++ return I;
+ }
+
+ // location - Allow the user to specify which external variable they want to
+ // store the results of the command line argument processing into, if they don't
+ // want to store it in the option itself.
+ //
+-template <class Ty> struct LocationClass {
++template <typename Ty> struct LocationClass {
+ Ty &Loc;
+- LocationClass(Ty &L) : Loc(L) {}
+
+- template <class Opt> void apply(Opt &O) const { O.setLocation(O, Loc); }
++ LocationClass(Ty &L) : Loc(L) { }
++ LocationClass(const LocationClass &RHS) : Loc(RHS.Loc) { }
++ LocationClass(LocationClass &&RHS) : Loc(RHS.Loc) { }
++
++ template<typename Opt>
++ void apply(Opt &O) const { O.setLocation(O, Loc); }
+ };
+
+-template <class Ty> LocationClass<Ty> location(Ty &L) {
++template <typename Ty> LocationClass<Ty> location(Ty &L) {
+ return LocationClass<Ty>(L);
+ }
+
+@@ -334,17 +462,22 @@
+ // to.
+ struct cat {
+ OptionCategory &Category;
+- cat(OptionCategory &c) : Category(c) {}
+
+- template <class Opt> void apply(Opt &O) const { O.setCategory(Category); }
++ cat(OptionCategory &c) : Category(c) { }
++ cat(const cat &RHS) : Category(RHS.Category) { }
++ virtual ~cat() { }
++
++ template <typename Opt>
++ void apply(Opt &O) const { O.setCategory(Category); }
+ };
+
+ //===----------------------------------------------------------------------===//
+ // OptionValue class
+
+ // Support value comparison outside the template.
+-struct GenericOptionValue {
+- virtual ~GenericOptionValue() {}
++class GenericOptionValue {
++public:
++ virtual ~GenericOptionValue() { }
+ virtual bool compare(const GenericOptionValue &V) const = 0;
+
+ private:
+@@ -458,57 +591,6 @@
+ };
+
+ //===----------------------------------------------------------------------===//
+-// Enum valued command line option
+-//
+-#define clEnumVal(ENUMVAL, DESC) #ENUMVAL, int(ENUMVAL), DESC
+-#define clEnumValN(ENUMVAL, FLAGNAME, DESC) FLAGNAME, int(ENUMVAL), DESC
+-#define clEnumValEnd (reinterpret_cast<void *>(0))
+-
+-// values - For custom data types, allow specifying a group of values together
+-// as the values that go into the mapping that the option handler uses. Note
+-// that the values list must always have a 0 at the end of the list to indicate
+-// that the list has ended.
+-//
+-template <class DataType> class ValuesClass {
+- // Use a vector instead of a map, because the lists should be short,
+- // the overhead is less, and most importantly, it keeps them in the order
+- // inserted so we can print our option out nicely.
+- SmallVector<std::pair<const char *, std::pair<int, const char *>>, 4> Values;
+- void processValues(va_list Vals);
+-
+-public:
+- ValuesClass(const char *EnumName, DataType Val, const char *Desc,
+- va_list ValueArgs) {
+- // Insert the first value, which is required.
+- Values.push_back(std::make_pair(EnumName, std::make_pair(Val, Desc)));
+-
+- // Process the varargs portion of the values...
+- while (const char *enumName = va_arg(ValueArgs, const char *)) {
+- DataType EnumVal = static_cast<DataType>(va_arg(ValueArgs, int));
+- const char *EnumDesc = va_arg(ValueArgs, const char *);
+- Values.push_back(std::make_pair(enumName, // Add value to value map
+- std::make_pair(EnumVal, EnumDesc)));
+- }
+- }
+-
+- template <class Opt> void apply(Opt &O) const {
+- for (size_t i = 0, e = Values.size(); i != e; ++i)
+- O.getParser().addLiteralOption(Values[i].first, Values[i].second.first,
+- Values[i].second.second);
+- }
+-};
+-
+-template <class DataType>
+-ValuesClass<DataType> LLVM_END_WITH_NULL
+-values(const char *Arg, DataType Val, const char *Desc, ...) {
+- va_list ValueArgs;
+- va_start(ValueArgs, Desc);
+- ValuesClass<DataType> Vals(Arg, Val, Desc, ValueArgs);
+- va_end(ValueArgs);
+- return Vals;
+-}
+-
+-//===----------------------------------------------------------------------===//
+ // parser class - Parameterizable parser for different data types. By default,
+ // known data types (string, int, bool) have specialized parsers, that do what
+ // you would expect. The default parser, used for data types that are not
+@@ -519,18 +601,23 @@
+ // generic_parser_base - This class holds all the non-generic code that we do
+ // not need replicated for every instance of the generic parser. This also
+ // allows us to put stuff into CommandLine.cpp
++// Moved here for an obvious reason.
+ //
+ class generic_parser_base {
+ protected:
+ class GenericOptionInfo {
+ public:
+ GenericOptionInfo(const char *name, const char *helpStr)
+- : Name(name), HelpStr(helpStr) {}
++ : Name(name), HelpStr(helpStr) {}
++ virtual ~GenericOptionInfo() { }
++
+ const char *Name;
+ const char *HelpStr;
+ };
+
+ public:
++ generic_parser_base() : hasArgStr(false) { }
++
+ virtual ~generic_parser_base() {} // Base class should have virtual-dtor
+
+ // getNumOptions - Virtual function implemented by generic subclass to
+@@ -576,7 +663,7 @@
+ hasArgStr = O.hasArgStr();
+ }
+
+- void getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) {
++ void getExtraOptionNames(std::vector<const char *> &OptionNames) {
+ // If there has been no argstr specified, that means that we need to add an
+ // argument for every possible option. This ensures that our options are
+ // vectored to us.
+@@ -612,34 +699,48 @@
+ bool hasArgStr;
+ };
+
++
+ // Default parser implementation - This implementation depends on having a
+ // mapping of recognized options to values of some sort. In addition to this,
+ // each entry in the mapping also tracks a help message that is printed with the
+ // command line option for -help. Because this is a simple mapping parser, the
+ // data type can be any unsupported type.
+ //
+-template <class DataType> class parser : public generic_parser_base {
++template <typename DataType>
++class parser : public generic_parser_base {
+ protected:
+ class OptionInfo : public GenericOptionInfo {
+ public:
+- OptionInfo(const char *name, DataType v, const char *helpStr)
+- : GenericOptionInfo(name, helpStr), V(v) {}
++ OptionInfo(const char *Name, DataType DT, const char *helpStr)
++ : GenericOptionInfo(Name, helpStr), V(DT) {}
++ ~OptionInfo() { }
++
+ OptionValue<DataType> V;
+ };
+- SmallVector<OptionInfo, 8> Values;
++
++ std::vector<OptionInfo> Values;
+
+ public:
+ typedef DataType parser_data_type;
+
++ parser<DataType>() : generic_parser_base(), Values() { }
++ virtual ~parser<DataType>() { }
++
+ // Implement virtual functions needed by generic_parser_base
+- unsigned getNumOptions() const override { return unsigned(Values.size()); }
+- const char *getOption(unsigned N) const override { return Values[N].Name; }
+- const char *getDescription(unsigned N) const override {
++ virtual unsigned getNumOptions() const override {
++ return static_cast<unsigned>(Values.size());
++ }
++
++ virtual const char *getOption(unsigned N) const override {
++ return Values[N].Name;
++ }
++
++ virtual const char *getDescription(unsigned N) const override {
+ return Values[N].HelpStr;
+ }
+
+ // getOptionValue - Return the value of option name N.
+- const GenericOptionValue &getOptionValue(unsigned N) const override {
++ virtual const GenericOptionValue &getOptionValue(unsigned N) const override {
+ return Values[N].V;
+ }
+
+@@ -662,7 +763,7 @@
+
+ /// addLiteralOption - Add an entry to the mapping table.
+ ///
+- template <class DT>
++ template<typename DT>
+ void addLiteralOption(const char *Name, const DT &V, const char *HelpStr) {
+ assert(findOption(Name) == Values.size() && "Option already exists!");
+ OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
+@@ -670,6 +771,14 @@
+ MarkOptionsChanged();
+ }
+
++ void addLiteralOption(const char *Name, const DataType &V,
++ const char *HelpStr) {
++ assert(findOption(Name) == Values.size() && "Option already exists!");
++ OptionInfo X(Name, V, HelpStr);
++ Values.push_back(X);
++ MarkOptionsChanged();
++ }
++
+ /// removeLiteralOption - Remove the specified option.
+ ///
+ void removeLiteralOption(const char *Name) {
+@@ -679,18 +788,95 @@
+ }
+ };
+
++//===----------------------------------------------------------------------===//
++// Enum valued command line option
++//
++#define clEnumVal(ENUMVAL, DESC) #ENUMVAL, int(ENUMVAL), DESC
++#define clEnumValN(ENUMVAL, FLAGNAME, DESC) FLAGNAME, int(ENUMVAL), DESC
++#define clEnumValEnd (reinterpret_cast<void *>(0))
++
++// values - For custom data types, allow specifying a group of values together
++// as the values that go into the mapping that the option handler uses. Note
++// that the values list must always have a 0 at the end of the list to indicate
++// that the list has ended.
++//
++template <typename DataType>
++class ValuesClass {
++ // Use a vector instead of a map, because the lists should be short,
++ // the overhead is less, and most importantly, it keeps them in the order
++ // inserted so we can print our option out nicely.
++ std::vector<std::pair<const char*, std::pair<int, const char*> > > Values;
++ void processValues(va_list Vals);
++
++public:
++ ValuesClass(const char *EnumName, DataType Val, const char *Desc,
++ va_list ValueArgs) : Values() {
++ // Insert the first value, which is required.
++ Values.push_back(std::make_pair(EnumName, std::make_pair(Val, Desc)));
++
++ // Process the varargs portion of the values...
++ while (const char *enumName = va_arg(ValueArgs, const char *)) {
++ DataType EnumVal = static_cast<DataType>(va_arg(ValueArgs, int));
++ const char *EnumDesc = va_arg(ValueArgs, const char *);
++
++ Values.push_back(std::make_pair(enumName, // Add value to value map
++ std::make_pair(EnumVal, EnumDesc)));
++ }
++ }
++
++ ValuesClass(const ValuesClass &RHS)
++ : Values(RHS.Values) { }
++
++ ValuesClass(ValuesClass &&RHS)
++ : Values(RHS.Values) { }
++
++ ValuesClass &operator=(const ValuesClass &RHS) {
++ if (this != &RHS)
++ Values.operator=(RHS.Values);
++
++ return *this;
++ }
++
++ ValuesClass &operator=(ValuesClass &&RHS) {
++ if (this != &RHS)
++ Values.operator=(RHS.Values);
++
++ return *this;
++ }
++
++ ~ValuesClass() { }
++
++ template <typename Opt> void apply(Opt &O) const {
++ for (size_t i = 0, e = Values.size(); i != e; ++i) {
++ O.getParser().addLiteralOption(Values[i].first, Values[i].second.first,
++ Values[i].second.second);
++ }
++ }
++};
++
++template <class DataType>
++ValuesClass<DataType> LLVM_END_WITH_NULL
++values(const char *Arg, DataType Val, const char *Desc, ...) {
++ va_list ValueArgs;
++ va_start(ValueArgs, Desc);
++ ValuesClass<DataType> Vals(Arg, Val, Desc, ValueArgs);
++ va_end(ValueArgs);
++ return Vals;
++}
++
+ //--------------------------------------------------
+ // basic_parser - Super class of parsers to provide boilerplate code
+ //
+ class basic_parser_impl { // non-template implementation of basic_parser<t>
+ public:
++ basic_parser_impl() { }
+ virtual ~basic_parser_impl() {}
+
+ enum ValueExpected getValueExpectedFlagDefault() const {
+ return ValueRequired;
+ }
+
+- void getExtraOptionNames(SmallVectorImpl<const char *> &) {}
++ void getExtraOptionNames(std::vector<const char *> &V) { }
+
+ void initialize(Option &) {}
+
+@@ -720,10 +906,46 @@
+ // basic_parser - The real basic parser is just a template wrapper that provides
+ // a typedef for the provided data type.
+ //
+-template <class DataType> class basic_parser : public basic_parser_impl {
++template <typename DataType>
++class basic_parser : public basic_parser_impl {
+ public:
++ basic_parser<DataType>() : basic_parser_impl(), Values() { }
++ ~basic_parser<DataType>() { }
++
++ unsigned getNumOptions() const {
++ return static_cast<unsigned>(Values.size());
++ }
++
++ const char *getOption(unsigned I) {
++ assert(I < static_cast<unsigned>(Values.size()) &&
++ "Index is out-of-range!");
++ return Values[I].Name;
++ }
++
++ const char *getDescription(unsigned I) {
++ assert(I < static_cast<unsigned>(Values.size()) &&
++ "Index is out-of-range!");
++ return Values[I].Help;
++ }
++
+ typedef DataType parser_data_type;
+ typedef OptionValue<DataType> OptVal;
++
++protected:
++ template<typename SameDataType>
++ class OptionInfo {
++ public:
++ OptionInfo(const char *NameStr, SameDataType DT, const char *HelpStr)
++ : Name(NameStr), Help(HelpStr), V(DT) { }
++
++ ~OptionInfo() { }
++
++ const char *Name;
++ const char *Help;
++ OptionValue<SameDataType> V;
++ };
++
++ std::vector<OptionInfo<DataType> > Values;
+ };
+
+ //--------------------------------------------------
+@@ -733,6 +955,9 @@
+ const char *ArgStr;
+
+ public:
++ parser<bool>() : basic_parser<bool>() { }
++ virtual ~parser<bool>() { }
++
+ // parse - Return true on error.
+ bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val);
+
+@@ -745,11 +970,17 @@
+ // getValueName - Do not print =<value> at all.
+ const char *getValueName() const override { return nullptr; }
+
++ void addLiteralOption(const char *Name, bool V, const char *HelpStr) {
++ OptionInfo<bool> OI(Name, V, HelpStr);
++ Values.push_back(OI);
++ MarkOptionsChanged();
++ }
++
+ void printOptionDiff(const Option &O, bool V, OptVal Default,
+ size_t GlobalWidth) const;
+
+ // An out-of-line virtual method to provide a 'home' for this class.
+- void anchor() override;
++ virtual void anchor() override;
+ };
+
+ EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<bool>);
+@@ -758,6 +989,9 @@
+ // parser<boolOrDefault>
+ template <> class parser<boolOrDefault> : public basic_parser<boolOrDefault> {
+ public:
++ parser<boolOrDefault>() : basic_parser<boolOrDefault>() { }
++ virtual ~parser<boolOrDefault>() { }
++
+ // parse - Return true on error.
+ bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val);
+
+@@ -772,7 +1006,7 @@
+ size_t GlobalWidth) const;
+
+ // An out-of-line virtual method to provide a 'home' for this class.
+- void anchor() override;
++ virtual void anchor() override;
+ };
+
+ EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
+@@ -782,12 +1016,21 @@
+ //
+ template <> class parser<int> : public basic_parser<int> {
+ public:
++ parser<int>() : basic_parser<int>() { }
++ virtual ~parser<int>() { }
++
+ // parse - Return true on error.
+ bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val);
+
+ // getValueName - Overload in subclass to provide a better default value.
+ const char *getValueName() const override { return "int"; }
+
++ void addLiteralOption(const char *Name, int V, const char *HelpStr) {
++ OptionInfo<int> OI(Name, V, HelpStr);
++ Values.push_back(OI);
++ MarkOptionsChanged();
++ }
++
+ void printOptionDiff(const Option &O, int V, OptVal Default,
+ size_t GlobalWidth) const;
+
+@@ -802,12 +1045,21 @@
+ //
+ template <> class parser<unsigned> : public basic_parser<unsigned> {
+ public:
++ parser<unsigned>() : basic_parser<unsigned>() { }
++ virtual ~parser<unsigned>() { }
++
+ // parse - Return true on error.
+ bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val);
+
+ // getValueName - Overload in subclass to provide a better default value.
+ const char *getValueName() const override { return "uint"; }
+
++ void addLiteralOption(const char *Name, unsigned V, const char *HelpStr) {
++ OptionInfo<unsigned> OI(Name, V, HelpStr);
++ Values.push_back(OI);
++ MarkOptionsChanged();
++ }
++
+ void printOptionDiff(const Option &O, unsigned V, OptVal Default,
+ size_t GlobalWidth) const;
+
+@@ -823,6 +1075,9 @@
+ template <>
+ class parser<unsigned long long> : public basic_parser<unsigned long long> {
+ public:
++ parser<unsigned long long>() : basic_parser<unsigned long long>() { }
++ virtual ~parser<unsigned long long>() { }
++
+ // parse - Return true on error.
+ bool parse(Option &O, StringRef ArgName, StringRef Arg,
+ unsigned long long &Val);
+@@ -844,6 +1099,9 @@
+ //
+ template <> class parser<double> : public basic_parser<double> {
+ public:
++ parser<double>() : basic_parser<double>() { }
++ virtual ~parser<double>() { }
++
+ // parse - Return true on error.
+ bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val);
+
+@@ -864,6 +1122,9 @@
+ //
+ template <> class parser<float> : public basic_parser<float> {
+ public:
++ parser<float>() : basic_parser<float>() { }
++ virtual ~parser<float>() { }
++
+ // parse - Return true on error.
+ bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val);
+
+@@ -884,6 +1145,9 @@
+ //
+ template <> class parser<std::string> : public basic_parser<std::string> {
+ public:
++ parser<std::string>() : basic_parser<std::string>() { }
++ virtual ~parser<std::string>() { }
++
+ // parse - Return true on error.
+ bool parse(Option &, StringRef, StringRef Arg, std::string &Value) {
+ Value = Arg.str();
+@@ -893,7 +1157,13 @@
+ // getValueName - Overload in subclass to provide a better default value.
+ const char *getValueName() const override { return "string"; }
+
+- void printOptionDiff(const Option &O, StringRef V, OptVal Default,
++ void addLiteralOption(const char *Name, int V, const char *HelpStr) {
++ OptionInfo<std::string> OI(Name, std::to_string(V), HelpStr);
++ Values.push_back(OI);
++ MarkOptionsChanged();
++ }
++
++ void printOptionDiff(const Option &O, const std::string &V, OptVal Default,
+ size_t GlobalWidth) const;
+
+ // An out-of-line virtual method to provide a 'home' for this class.
+@@ -907,6 +1177,9 @@
+ //
+ template <> class parser<char> : public basic_parser<char> {
+ public:
++ parser<char>() : basic_parser<char>() { }
++ virtual ~parser<char>() { }
++
+ // parse - Return true on error.
+ bool parse(Option &, StringRef, StringRef Arg, char &Value) {
+ Value = Arg[0];
+@@ -916,6 +1189,12 @@
+ // getValueName - Overload in subclass to provide a better default value.
+ const char *getValueName() const override { return "char"; }
+
++ void addLiteralOption(const char *Name, char V, const char *HelpStr) {
++ OptionInfo<char> OI(Name, V, HelpStr);
++ Values.push_back(OI);
++ MarkOptionsChanged();
++ }
++
+ void printOptionDiff(const Option &O, char V, OptVal Default,
+ size_t GlobalWidth) const;
+
+@@ -976,8 +1255,9 @@
+ // not correctly respond to the apply method). Because the syntax to use this
+ // is a pain, we have the 'apply' method below to handle the nastiness...
+ //
+-template <class Mod> struct applicator {
+- template <class Opt> static void opt(const Mod &M, Opt &O) { M.apply(O); }
++template <typename Mod> struct applicator {
++ template <typename Opt>
++ static void opt(const Mod &M, Opt &O) { M.apply(O); }
+ };
+
+ // Handle const char* as a special case...
+@@ -1039,11 +1319,16 @@
+ }
+
+ public:
+- opt_storage() : Location(nullptr) {}
++ opt_storage() : Location(nullptr), Default() { }
++ opt_storage(const opt_storage &RHS)
++ : Location(RHS.Location), Default(RHS.Default) { }
++ opt_storage(opt_storage &&RHS)
++ : Location(RHS.Location), Default(RHS.Default) { }
+
+ bool setLocation(Option &O, DataType &L) {
+ if (Location)
+ return O.error("cl::location(x) specified more than once!");
++
+ Location = &L;
+ Default = L;
+ return false;
+@@ -1077,8 +1362,47 @@
+ template <class DataType>
+ class opt_storage<DataType, false, true> : public DataType {
+ public:
++ opt_storage() : DataType(), Location(nullptr), Default() { }
++ opt_storage(const opt_storage &RHS)
++ : DataType(RHS), Location(RHS.Location), Default(RHS.Default) { }
++ opt_storage(opt_storage &&RHS)
++ : DataType(RHS), Location(RHS.Location), Default(RHS.Default) { }
++
++ opt_storage<DataType, false, true>
++ &operator=(const opt_storage<DataType, false, true> &RHS) {
++ if (this != &RHS) {
++ DataType::operator=(RHS);
++ Location = RHS.Location;
++ Default = RHS.Default;
++ }
++
++ return *this;
++ }
++
++ opt_storage<DataType, false, true>
++ &operator=(opt_storage<DataType, false, true> &&RHS) {
++ if (this != &RHS) {
++ DataType::operator=(RHS);
++ Location = RHS.Location;
++ Default = RHS.Default;
++ }
++
++ return *this;
++ }
++
++
++ DataType *Location;
+ OptionValue<DataType> Default;
+
++ bool setLocation(Option &O, DataType &L) {
++ if (Location)
++ return O.error("cl::location(x) specified more than once!");
++
++ Location = &L;
++ Default = L;
++ return false;
++ }
++
+ template <class T> void setValue(const T &V, bool initial = false) {
+ DataType::operator=(V);
+ if (initial)
+@@ -1102,13 +1426,45 @@
+
+ // Make sure we initialize the value with the default constructor for the
+ // type.
+- opt_storage() : Value(DataType()), Default(DataType()) {}
++ opt_storage() : Value(DataType()), Default(DataType()) { }
++ opt_storage(const opt_storage &RHS)
++ : Value(RHS.Value), Default(RHS.Default) { }
++ opt_storage(opt_storage &&RHS)
++ : Value(RHS.Location), Default(RHS.Default) { }
++
++ opt_storage<DataType, false, false>
++ &operator=(const opt_storage<DataType, false, false> &RHS) {
++ if (this != &RHS) {
++ Value = RHS.Value;
++ Default = RHS.Default;
++ }
++
++ return *this;
++ }
++
++ opt_storage<DataType, false, false>
++ &operator=(opt_storage<DataType, false, false> &&RHS) {
++ if (this != &RHS) {
++ Value = RHS.Value;
++ Default = RHS.Default;
++ }
++
++ return *this;
++ }
++
++
++ bool setLocation(Option &O, DataType &L) {
++ Value = L;
++ Default = Value;
++ return false;
++ }
+
+ template <class T> void setValue(const T &V, bool initial = false) {
+ Value = V;
+ if (initial)
+ Default = V;
+ }
++
+ DataType &getValue() { return Value; }
+ DataType getValue() const { return Value; }
+
+@@ -1123,19 +1479,21 @@
+ //===----------------------------------------------------------------------===//
+ // opt - A scalar command line option.
+ //
+-template <class DataType, bool ExternalStorage = false,
+- class ParserClass = parser<DataType>>
++template <typename DataType, bool ExternalStorage = false,
++ typename ParserClass = parser<DataType> >
+ class opt : public Option,
+ public opt_storage<DataType, ExternalStorage,
+ std::is_class<DataType>::value> {
+ ParserClass Parser;
+
+- bool handleOccurrence(unsigned pos, StringRef ArgName,
+- StringRef Arg) override {
++protected:
++ virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
++ StringRef Arg) override {
+ typename ParserClass::parser_data_type Val =
+ typename ParserClass::parser_data_type();
+ if (Parser.parse(*this, ArgName, Arg, Val))
+ return true; // Parse error!
++
+ this->setValue(Val);
+ this->setPosition(pos);
+ return false;
+@@ -1145,7 +1503,7 @@
+ return Parser.getValueExpectedFlagDefault();
+ }
+ void
+- getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) override {
++ getExtraOptionNames(std::vector<const char *> &OptionNames) override {
+ return Parser.getExtraOptionNames(OptionNames);
+ }
+
+@@ -1170,11 +1528,33 @@
+ }
+
+ public:
++ opt() : Option(), opt_storage<DataType, ExternalStorage,
++ std::is_class<DataType>::value>(),
++ Parser() { }
++
++ opt(const opt &RHS) : Option(RHS),
++ opt_storage<DataType, ExternalStorage,
++ std::is_class<DataType>::value>(RHS),
++ Parser(RHS.Parser) { }
++
++ ~opt() { }
++
+ // setInitialValue - Used by the cl::init modifier...
+ void setInitialValue(const DataType &V) { this->setValue(V, true); }
+
+ ParserClass &getParser() { return Parser; }
+
++ bool setLocation(Option &O, DataType &L) {
++ bool R = opt_storage<DataType, ExternalStorage,
++ std::is_class<DataType>::value>::setLocation(O, L);
++ return R;
++ }
++
++ void addArgument() {
++ assert(!NextRegistered && "argument multiply registered!");
++ Option::registerOption(this);
++ }
++
+ template <class T> DataType &operator=(const T &Val) {
+ this->setValue(Val);
+ return this->getValue();
+@@ -1271,6 +1651,23 @@
+ apply(M7, this);
+ done();
+ }
++ // Nine options...
++ template <class M0t, class M1t, class M2t, class M3t, class M4t, class M5t,
++ class M6t, class M7t, class M8t>
++ opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3, const M4t &M4,
++ const M5t &M5, const M6t &M6, const M7t &M7, const M8t &M8)
++ : Option(Optional, NotHidden) {
++ apply(M0, this);
++ apply(M1, this);
++ apply(M2, this);
++ apply(M3, this);
++ apply(M4, this);
++ apply(M5, this);
++ apply(M6, this);
++ apply(M7, this);
++ apply(M8, this);
++ done();
++ }
+ };
+
+ EXTERN_TEMPLATE_INSTANTIATION(class opt<unsigned>);
+@@ -1291,10 +1688,12 @@
+
+ public:
+ list_storage() : Location(0) {}
++ virtual ~list_storage() { }
+
+ bool setLocation(Option &O, StorageClass &L) {
+ if (Location)
+ return O.error("cl::location(x) specified more than once!");
++
+ Location = &L;
+ return false;
+ }
+@@ -1312,9 +1711,38 @@
+ //
+ template <class DataType>
+ class list_storage<DataType, bool> : public std::vector<DataType> {
++private:
++ list_storage<DataType, bool>(list_storage<DataType, bool> &&RHS) LLVM_DELETED_FUNCTION;
++ list_storage<DataType, bool>
++ &&operator=(list_storage<DataType, bool> &&RHS) LLVM_DELETED_FUNCTION;
++
+ public:
++ list_storage<DataType, bool>() : std::vector<DataType>() { }
++ list_storage<DataType, bool>(const list_storage<DataType, bool> &RHS)
++ : std::vector<DataType>(RHS) { }
++ list_storage<DataType, bool>
++ &operator=(const list_storage<DataType, bool> &RHS) {
++ if (this != &RHS)
++ std::vector<DataType>::operator=(RHS);
++
++ return *this;
++ }
++
++ virtual ~list_storage<DataType, bool>() { }
++
+ template <class T> void addValue(const T &V) {
+- std::vector<DataType>::push_back(V);
++ T LV(V);
++ this->push_back(LV);
++ }
++
++ void addValue(const DataType &V) {
++ DataType LV(V);
++ std::vector<DataType> &VEC = static_cast<std::vector<DataType>& >(*this);
++ VEC.push_back(LV);
++ }
++
++ const std::vector<DataType> &getStorage() const {
++ return static_cast<const std::vector<DataType>& >(*this);
+ }
+ };
+
+@@ -1324,40 +1752,47 @@
+ template <class DataType, class Storage = bool,
+ class ParserClass = parser<DataType>>
+ class list : public Option, public list_storage<DataType, Storage> {
++ friend class Option;
++
+ std::vector<unsigned> Positions;
+ ParserClass Parser;
+
+- enum ValueExpected getValueExpectedFlagDefault() const override {
++protected:
++ virtual enum ValueExpected getValueExpectedFlagDefault() const override {
+ return Parser.getValueExpectedFlagDefault();
+ }
+- void
+- getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) override {
++
++ virtual void
++ getExtraOptionNames(std::vector<const char *> &OptionNames) override {
+ return Parser.getExtraOptionNames(OptionNames);
+ }
+
+- bool handleOccurrence(unsigned pos, StringRef ArgName,
+- StringRef Arg) override {
++ virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
++ StringRef Arg) override {
+ typename ParserClass::parser_data_type Val =
+ typename ParserClass::parser_data_type();
++
+ if (Parser.parse(*this, ArgName, Arg, Val))
+ return true; // Parse Error!
+- list_storage<DataType, Storage>::addValue(Val);
++
++ this->addValue(Val);
+ setPosition(pos);
+ Positions.push_back(pos);
+ return false;
+ }
+
+ // Forward printing stuff to the parser...
+- size_t getOptionWidth() const override {
++ virtual size_t getOptionWidth() const override {
+ return Parser.getOptionWidth(*this);
+ }
+- void printOptionInfo(size_t GlobalWidth) const override {
++
++ virtual void printOptionInfo(size_t GlobalWidth) const override {
+ Parser.printOptionInfo(*this, GlobalWidth);
+ }
+
+ // Unimplemented: list options don't currently store their default value.
+- void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
+- }
++ virtual void
++ printOptionValue(size_t GlobalWidth, bool Force) const override { }
+
+ void done() {
+ addArgument();
+@@ -1365,8 +1800,26 @@
+ }
+
+ public:
++ list() : Option(), list_storage<DataType, Storage>(),
++ Positions(), Parser(ParserClass()) { }
++
++ list(const Option &O)
++ : Option(O), list_storage<DataType, Storage>(),
++ Positions(), Parser(ParserClass()) { }
++
++ list(Option *O)
++ : Option(*O), list_storage<DataType, Storage>(),
++ Positions(), Parser(ParserClass()) { }
++
++ ~list() { }
++
+ ParserClass &getParser() { return Parser; }
+
++ void addArgument() {
++ assert(!NextRegistered && "argument multiply registered!");
++ Option::registerOption(this);
++ }
++
+ unsigned getPosition(unsigned optnum) const {
+ assert(optnum < this->size() && "Invalid option index");
+ return Positions[optnum];
+@@ -1500,6 +1953,7 @@
+ bool setLocation(Option &O, unsigned &L) {
+ if (Location)
+ return O.error("cl::location(x) specified more than once!");
++
+ Location = &L;
+ return false;
+ }
+@@ -1551,12 +2005,12 @@
+ return Parser.getValueExpectedFlagDefault();
+ }
+ void
+- getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) override {
++ getExtraOptionNames(std::vector<const char *> &OptionNames) override {
+ return Parser.getExtraOptionNames(OptionNames);
+ }
+
+- bool handleOccurrence(unsigned pos, StringRef ArgName,
+- StringRef Arg) override {
++ virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
++ StringRef Arg) override {
+ typename ParserClass::parser_data_type Val =
+ typename ParserClass::parser_data_type();
+ if (Parser.parse(*this, ArgName, Arg, Val))
+@@ -1690,14 +2144,17 @@
+
+ class alias : public Option {
+ Option *AliasFor;
+- bool handleOccurrence(unsigned pos, StringRef /*ArgName*/,
+- StringRef Arg) override {
++ virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
++ StringRef Arg) override {
++
+ return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
+ }
+- bool addOccurrence(unsigned pos, StringRef /*ArgName*/, StringRef Value,
+- bool MultiArg = false) override {
++
++ virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
++ bool MultiArg = false) override {
+ return AliasFor->addOccurrence(pos, AliasFor->ArgStr, Value, MultiArg);
+ }
++
+ // Handle printing stuff...
+ size_t getOptionWidth() const override;
+ void printOptionInfo(size_t GlobalWidth) const override;
+@@ -1847,7 +2304,7 @@
+ /// lines and end of the response file to be marked with a nullptr string.
+ /// \param [out] NewArgv All parsed strings are appended to NewArgv.
+ void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver,
+- SmallVectorImpl<const char *> &NewArgv,
++ std::vector<const char *> &NewArgv,
+ bool MarkEOLs = false);
+
+ /// \brief Tokenizes a Windows command line which may contain quotes and escaped
+@@ -1862,13 +2319,13 @@
+ /// lines and end of the response file to be marked with a nullptr string.
+ /// \param [out] NewArgv All parsed strings are appended to NewArgv.
+ void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver,
+- SmallVectorImpl<const char *> &NewArgv,
++ std::vector<const char *> &NewArgv,
+ bool MarkEOLs = false);
+
+ /// \brief String tokenization function type. Should be compatible with either
+ /// Windows or Unix command line tokenizers.
+ typedef void (*TokenizerCallback)(StringRef Source, StringSaver &Saver,
+- SmallVectorImpl<const char *> &NewArgv,
++ std::vector<const char *> &NewArgv,
+ bool MarkEOLs);
+
+ /// \brief Expand response files on a command line recursively using the given
+@@ -1886,7 +2343,7 @@
+ /// with nullptrs in the Argv vector.
+ /// \return true if all @files were expanded successfully or there were none.
+ bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
+- SmallVectorImpl<const char *> &Argv,
++ std::vector<const char *> &Argv,
+ bool MarkEOLs = false);
+
+ } // End namespace cl
+--- include/llvm/Support/FileSystem.h 2014-12-15 19:10:29.000000000 -0800
++++ include/llvm/Support/FileSystem.h 2016-01-24 21:14:49.000000000 -0800
+@@ -680,10 +680,35 @@
+
+ public:
+ explicit directory_entry(const Twine &path, file_status st = file_status())
+- : Path(path.str())
+- , Status(st) {}
++ : Path(path.str()), Status(st) { }
+
+- directory_entry() {}
++ directory_entry() : Path(""), Status(file_status()) { }
++
++ directory_entry(const directory_entry &rhs)
++ : Path(rhs.Path), Status(rhs.Status) { }
++
++ directory_entry(directory_entry &&rhs)
++ : Path(rhs.Path), Status(rhs.Status) { }
++
++ ~directory_entry() { }
++
++ directory_entry &operator=(const directory_entry &rhs) {
++ if (this != &rhs) {
++ Path = rhs.Path;
++ Status = rhs.Status;
++ }
++
++ return *this;
++ }
++
++ directory_entry &operator=(directory_entry &&rhs) {
++ if (this != &rhs) {
++ Path = rhs.Path;
++ Status = rhs.Status;
++ }
++
++ return *this;
++ }
+
+ void assign(const Twine &path, file_status st = file_status()) {
+ Path = path.str();
+--- include/llvm/Support/PluginLoader.h 2007-12-29 11:59:42.000000000 -0800
++++ include/llvm/Support/PluginLoader.h 2016-01-24 11:01:53.000000000 -0800
+@@ -22,6 +22,8 @@
+ namespace llvm {
+ struct PluginLoader {
+ void operator=(const std::string &Filename);
++ bool operator==(const std::string &Filename) const;
++ bool operator!=(const std::string &Filename) const;
+ static unsigned getNumPlugins();
+ static std::string& getPlugin(unsigned num);
+ };
+--- utils/TableGen/AsmMatcherEmitter.cpp 2015-01-03 00:16:29.000000000 -0800
++++ utils/TableGen/AsmMatcherEmitter.cpp 2016-01-26 14:57:52.000000000 -0800
+@@ -121,7 +121,7 @@
+ #define DEBUG_TYPE "asm-matcher-emitter"
+
+ static cl::opt<std::string>
+-MatchPrefix("match-prefix", cl::init(""),
++MatchPrefix("match-prefix", cl::init(std::string("")),
+ cl::desc("Only match instructions with the given prefix"));
+
+ namespace {
+--- tools/llc/llc.cpp 2014-12-11 23:52:06.000000000 -0800
++++ tools/llc/llc.cpp 2016-01-26 14:44:02.000000000 -0800
+@@ -50,13 +50,14 @@
+ // and back-end code generation options are specified with the target machine.
+ //
+ static cl::opt<std::string>
+-InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
++InputFilename(cl::Positional, cl::desc("<input bitcode>"),
++ cl::init(std::string("-")));
+
+ static cl::opt<std::string>
+ OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
+
+ static cl::opt<unsigned>
+-TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
++TimeCompilations("time-compilations", cl::Hidden, cl::init(1U),
+ cl::value_desc("N"),
+ cl::desc("Repeat compilation N times for timing"));
+
+@@ -65,13 +66,15 @@
+ cl::desc("Disable integrated assembler"));
+
+ // Determine optimization level.
++// ORIGINAL:
+ static cl::opt<char>
+ OptLevel("O",
+ cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
+ "(default = '-O2')"),
+ cl::Prefix,
+- cl::ZeroOrMore,
+- cl::init(' '));
++ cl::Optional,
++ cl::ValueRequired,
++ cl::init('2'));
+
+ static cl::opt<std::string>
+ TargetTriple("mtriple", cl::desc("Override target triple for module"));
+--- tools/llvm-as/llvm-as.cpp 2014-08-25 11:16:47.000000000 -0700
++++ tools/llvm-as/llvm-as.cpp 2016-01-26 15:07:18.000000000 -0800
+@@ -15,6 +15,8 @@
+ //
+ //===----------------------------------------------------------------------===//
+
++#include "llvm/Support/CommandLine.h"
++
+ #include "llvm/IR/LLVMContext.h"
+ #include "llvm/AsmParser/Parser.h"
+ #include "llvm/Bitcode/ReaderWriter.h"
+@@ -28,11 +30,21 @@
+ #include "llvm/Support/SourceMgr.h"
+ #include "llvm/Support/SystemUtils.h"
+ #include "llvm/Support/ToolOutputFile.h"
+-#include <memory>
+ using namespace llvm;
+
++#include <memory>
++#include <string>
++
++static cl::opt<std::string>
++HiddenOption("h", cl::Hidden, cl::desc("hidden option"),
++ cl::init(""));
++
+ static cl::opt<std::string>
+-InputFilename(cl::Positional, cl::desc("<input .llvm file>"), cl::init("-"));
++InputFilename(cl::Positional, cl::desc("<input file>"),
++ cl::NotHidden,
++ cl::Optional,
++ cl::init(std::string("-")),
++ cl::ValuePositionalNoArgs);
+
+ static cl::opt<std::string>
+ OutputFilename("o", cl::desc("Override output filename"),
+--- tools/llvm-dis/llvm-dis.cpp 2015-01-09 16:07:30.000000000 -0800
++++ tools/llvm-dis/llvm-dis.cpp 2016-02-01 12:08:04.531107200 -0800
+@@ -38,7 +38,8 @@
+ using namespace llvm;
+
+ static cl::opt<std::string>
+-InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
++InputFilename(cl::Positional, cl::desc("<input bitcode>"),
++ cl::init(std::string("-")));
+
+ static cl::opt<std::string>
+ OutputFilename("o", cl::desc("Override output filename"),
+--- tools/bugpoint/OptimizerDriver.cpp 2014-11-07 13:30:36.000000000 -0800
++++ tools/bugpoint/OptimizerDriver.cpp 2016-01-26 15:51:53.000000000 -0800
+@@ -46,7 +46,7 @@
+ // ChildOutput - This option captures the name of the child output file that
+ // is set up by the parent bugpoint process
+ cl::opt<std::string> ChildOutput("child-output", cl::ReallyHidden);
+- cl::opt<std::string> OptCmd("opt-command", cl::init(""),
++ cl::opt<std::string> OptCmd("opt-command", cl::init(std::string("")),
+ cl::desc("Path to opt. (default: search path "
+ "for 'opt'.)"));
+ }
+--- tools/opt/opt.cpp 2014-12-11 23:52:14.000000000 -0800
++++ tools/opt/opt.cpp 2016-01-26 14:43:37.000000000 -0800
+@@ -72,7 +72,7 @@
+ //
+ static cl::opt<std::string>
+ InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
+- cl::init("-"), cl::value_desc("filename"));
++ cl::init(std::string("-")), cl::value_desc("filename"));
+
+ static cl::opt<std::string>
+ OutputFilename("o", cl::desc("Override output filename"),
+@@ -175,7 +175,7 @@
+ static cl::opt<std::string>
+ DefaultDataLayout("default-data-layout",
+ cl::desc("data layout string to use if not specified by module"),
+- cl::value_desc("layout-string"), cl::init(""));
++ cl::value_desc("layout-string"), cl::init(std::string("")));
+
+
+
+--- unittests/Support/CommandLineTest.cpp 2014-08-22 12:29:17.000000000 -0700
++++ unittests/Support/CommandLineTest.cpp 2016-01-27 11:20:39.000000000 -0800
+@@ -7,12 +7,17 @@
+ //
+ //===----------------------------------------------------------------------===//
+
++#ifndef SKIP_ENVIRONMENT_TESTS
++#define SKIP_ENVIRONMENT_TESTS 1
++#endif
++
+ #include "llvm/ADT/STLExtras.h"
+ #include "llvm/Config/config.h"
+ #include "llvm/Support/CommandLine.h"
+ #include "gtest/gtest.h"
+ #include <stdlib.h>
+ #include <string>
++#include <vector>
+
+ using namespace llvm;
+
+@@ -47,21 +52,23 @@
+ typedef cl::opt<T> Base;
+ public:
+ // One option...
+- template<class M0t>
+- explicit StackOption(const M0t &M0) : Base(M0) {}
++ template<typename T0>
++ explicit StackOption(const T0 &M0) : cl::opt<T>(M0) { }
+
+ // Two options...
+- template<class M0t, class M1t>
+- StackOption(const M0t &M0, const M1t &M1) : Base(M0, M1) {}
++ template<typename T0, typename T1>
++ explicit StackOption(const T0 &M0, const T1 &M1) : cl::opt<T>(M0, M1) { }
+
+ // Three options...
+- template<class M0t, class M1t, class M2t>
+- StackOption(const M0t &M0, const M1t &M1, const M2t &M2) : Base(M0, M1, M2) {}
++ template<typename T0, typename T1, typename T2>
++ explicit StackOption(const T0 &M0, const T1 &M1, const T2 &M2)
++ : cl::opt<T>(M0, M1, M2) { }
+
+ // Four options...
+- template<class M0t, class M1t, class M2t, class M3t>
+- StackOption(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
+- : Base(M0, M1, M2, M3) {}
++ template<typename T0, typename T1, typename T2, typename T3>
++ explicit StackOption(const T0 &M0, const T1 &M1,
++ const T2 &M2, const T3 &M3)
++ : cl::opt<T>(M0, M1, M2, M3) { }
+
+ ~StackOption() {
+ this->removeArgument();
+@@ -112,7 +119,7 @@
+
+ const char test_env_var[] = "LLVM_TEST_COMMAND_LINE_FLAGS";
+
+-cl::opt<std::string> EnvironmentTestOption("env-test-opt");
++static cl::opt<std::string> EnvironmentTestOption("env-test-opt");
+ TEST(CommandLineTest, ParseEnvironment) {
+ TempEnvVar TEV(test_env_var, "-env-test-opt=hello");
+ EXPECT_EQ("", EnvironmentTestOption);
+@@ -153,12 +160,13 @@
+ };
+
+ typedef void ParserFunction(StringRef Source, llvm::cl::StringSaver &Saver,
+- SmallVectorImpl<const char *> &NewArgv,
++ std::vector<const char*> &NewArgv,
+ bool MarkEOLs);
+
+ void testCommandLineTokenizer(ParserFunction *parse, const char *Input,
+- const char *const Output[], size_t OutputSize) {
+- SmallVector<const char *, 0> Actual;
++ std::vector<const char*> &Output,
++ size_t OutputSize) {
++ std::vector<const char*> Actual;
+ StrDupSaver Saver;
+ parse(Input, Saver, Actual, /*MarkEOLs=*/false);
+ EXPECT_EQ(OutputSize, Actual.size());
+@@ -175,7 +183,12 @@
+ const char *const Output[] = { "foo bar", "foo bar", "foo bar", "foo\\bar",
+ "foobarbaz", "C:\\src\\foo.cpp",
+ "C:\\src\\foo.cpp" };
+- testCommandLineTokenizer(cl::TokenizeGNUCommandLine, Input, Output,
++
++ std::vector<const char*> OutputVector;
++ for (unsigned I = 0; I < array_lengthof(Output); ++I)
++ OutputVector.push_back(Output[I]);
++
++ testCommandLineTokenizer(cl::TokenizeGNUCommandLine, Input, OutputVector,
+ array_lengthof(Output));
+ }
+
+@@ -184,10 +197,17 @@
+ "\"st \\\"u\" \\v";
+ const char *const Output[] = { "a\\b", "c\\\\d", "e\\f g", "h\"i", "j\\\"k",
+ "lmn", "o", "pqr", "st \"u", "\\v" };
+- testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, Output,
++
++ std::vector<const char*> OutputVector;
++ for (unsigned I = 0; I < array_lengthof(Output); ++I)
++ OutputVector.push_back(Output[I]);
++
++ testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, OutputVector,
+ array_lengthof(Output));
+ }
+
++#ifndef ALIAS_WITH_ARGUMENT_TESTS_ARE_BROKEN
++// This test case is 100% broken.
+ TEST(CommandLineTest, AliasesWithArguments) {
+ static const size_t ARGC = 3;
+ const char *const Inputs[][ARGC] = {
+@@ -201,7 +221,6 @@
+ StackOption<std::string> Actual("actual");
+ StackOption<bool> Extra("extra");
+ StackOption<std::string> Input(cl::Positional);
+-
+ cl::alias Alias("alias", llvm::cl::aliasopt(Actual));
+
+ cl::ParseCommandLineOptions(ARGC, Inputs[i]);
+@@ -211,6 +230,7 @@
+ Alias.removeArgument();
+ }
+ }
++#endif
+
+ void testAliasRequired(int argc, const char *const *argv) {
+ StackOption<std::string> Option("option", cl::Required);
+--- utils/FileCheck/FileCheck.cpp 2014-11-18 18:56:00.000000000 -0800
++++ utils/FileCheck/FileCheck.cpp 2016-02-01 13:52:04.699904440 -0800
+@@ -40,7 +40,8 @@
+
+ static cl::opt<std::string>
+ InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
+- cl::init("-"), cl::value_desc("filename"));
++ cl::value_desc("filename"),
++ cl::init(std::string("-")));
+
+ static cl::list<std::string>
+ CheckPrefixes("check-prefix",
+--- include/llvm/LinkAllPasses.h 2015-01-14 03:23:27.000000000 -0800
++++ include/llvm/LinkAllPasses.h 2016-02-01 09:24:47.493918163 -0800
+@@ -15,6 +15,7 @@
+ #ifndef LLVM_LINKALLPASSES_H
+ #define LLVM_LINKALLPASSES_H
+
++#include "llvm/Analysis/AliasAnalysis.h"
+ #include "llvm/Analysis/AliasSetTracker.h"
+ #include "llvm/Analysis/CallPrinter.h"
+ #include "llvm/Analysis/DomPrinter.h"
+@@ -35,10 +36,12 @@
+ #include "llvm/Transforms/Utils/SymbolRewriter.h"
+ #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
+ #include "llvm/Transforms/Vectorize.h"
++
+ #include <cstdlib>
+
+ namespace {
+ struct ForcePassLinking {
++ __attribute__((used, noinline))
+ ForcePassLinking() {
+ // We must reference the passes in such a way that compilers will not
+ // delete it all as dead code, even with whole program optimization,
+@@ -47,6 +50,8 @@
+ if (std::getenv("bar") != (char*) -1)
+ return;
+
++ asm("");
++
+ (void) llvm::createAAEvalPass();
+ (void) llvm::createAggressiveDCEPass();
+ (void) llvm::createAliasAnalysisCounterPass();
+@@ -148,9 +153,13 @@
+ (void) llvm::createMetaRenamerPass();
+ (void) llvm::createFunctionAttrsPass();
+ (void) llvm::createMergeFunctionsPass();
+- (void) llvm::createPrintModulePass(*(llvm::raw_ostream*)nullptr);
+- (void) llvm::createPrintFunctionPass(*(llvm::raw_ostream*)nullptr);
+- (void) llvm::createPrintBasicBlockPass(*(llvm::raw_ostream*)nullptr);
++
++ std::string S;
++ llvm::raw_string_ostream RSO(S);
++
++ (void) llvm::createPrintModulePass(RSO);
++ (void) llvm::createPrintFunctionPass(RSO);
++ (void) llvm::createPrintBasicBlockPass(RSO);
+ (void) llvm::createModuleDebugInfoPrinterPass();
+ (void) llvm::createPartialInliningPass();
+ (void) llvm::createLintPass();
+@@ -167,13 +176,20 @@
+ (void) llvm::createSeparateConstOffsetFromGEPPass();
+ (void) llvm::createRewriteSymbolsPass();
+
+- (void)new llvm::IntervalPartition();
+- (void)new llvm::ScalarEvolution();
+- ((llvm::Function*)nullptr)->viewCFGOnly();
++ llvm::IntervalPartition *LIP = new llvm::IntervalPartition();
++ (void) LIP;
++
++ llvm::ScalarEvolution *LSE = new llvm::ScalarEvolution();
++ (void) LSE;
++
++ llvm::Function *F =
++ llvm::Function::Create(nullptr, llvm::GlobalValue::ExternalLinkage);
++ F->viewCFGOnly();
++
+ llvm::RGPassManager RGM;
+- ((llvm::RegionPass*)nullptr)->runOnRegion((llvm::Region*)nullptr, RGM);
+- llvm::AliasSetTracker X(*(llvm::AliasAnalysis*)nullptr);
+- X.add(nullptr, 0, llvm::AAMDNodes()); // for -print-alias-sets
++ llvm::AliasAnalysis LAA;
++ llvm::AliasSetTracker LAST(LAA);
++ LAST.add(nullptr, 0, llvm::AAMDNodes()); // for -print-alias-sets
+ }
+ } ForcePassLinking; // Force link by creating a global definition.
+ }
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/021-llvm-ilist-iterator-22031298.patch Wed Feb 10 11:54:12 2016 -0800
@@ -0,0 +1,13055 @@
+# http://lists.llvm.org/pipermail/llvm-dev/2015-October/091115.html
+# - 22031298 - toxic bugs in LLVM ilist/plist end up eliminating entire
+# MachineBasicBlocks
+# - Presumed fixed (?) in trunk upstream. Not verified.
+# - Verified fixed in our 3.6.2 fork.
+# Not for upstream. Autoconf-based built system is removed in 3.8.X.
+--- Makefile.rules 2015-10-05 11:01:32.687305595 -0700
++++ Makefile.rules 2015-12-08 11:12:41.094567698 -0800
+@@ -331,6 +331,12 @@
+ endif
+ endif
+
++ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
++ REQUIRES_EH := 1
++else
++ REQUIRES_EH := 0
++endif
++
+ ifeq ($(ENABLE_WERROR),1)
+ CXX.Flags += -Werror
+ C.Flags += -Werror
+@@ -355,14 +361,16 @@
+ endif
+
+ # IF REQUIRES_EH=1 is specified then don't disable exceptions
+-ifndef REQUIRES_EH
++ifneq ($(REQUIRES_EH), 1)
++ REQUIRES_RTTI := 0
+ CXX.Flags += -fno-exceptions
+ else
+ # If the library requires EH, it also requires RTTI.
+ REQUIRES_RTTI := 1
++ CXX.Flags += -fexceptions
+ endif
+
+-ifdef REQUIRES_FRAME_POINTER
++ifeq ($(REQUIRES_FRAME_POINTER), 1)
+ CXX.Flags := $(filter-out -fomit-frame-pointer,$(CXX.Flags))
+ C.Flags := $(filter-out -fomit-frame-pointer,$(C.Flags))
+ LD.Flags := $(filter-out -fomit-frame-pointer,$(LD.Flags))
+@@ -371,6 +379,8 @@
+ # If REQUIRES_RTTI=1 is specified then don't disable run-time type id.
+ ifneq ($(REQUIRES_RTTI), 1)
+ CXX.Flags += -fno-rtti
++else
++ CXX.Flags += -frtti
+ endif
+
+ ifeq ($(ENABLE_COVERAGE),1)
+--- include/llvm/ADT/DenseMap.h 2015-10-05 11:01:32.000000000 -0700
++++ include/llvm/ADT/DenseMap.h 2016-01-24 14:13:03.000000000 -0800
+@@ -254,7 +254,7 @@
+ DenseMapBase() {}
+
+ void destroyAll() {
+- if ((getNumBuckets() == 0) || empty()) // Nothing to do.
++ if (getNumBuckets() == 0) // Nothing to do.
+ return;
+
+ const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
+@@ -264,10 +264,6 @@
+ P->getSecond().~ValueT();
+ P->getFirst().~KeyT();
+ }
+-
+-#ifndef NDEBUG
+- memset((void*)getBuckets(), 0x5a, sizeof(BucketT)*getNumBuckets());
+-#endif
+ }
+
+ void initEmpty() {
+@@ -856,7 +852,8 @@
+
+ // First move the inline buckets into a temporary storage.
+ AlignedCharArrayUnion<BucketT[InlineBuckets]> TmpStorage;
+- BucketT *TmpBegin = reinterpret_cast<BucketT *>(TmpStorage.buffer);
++ BucketT *TmpBegin =
++ reinterpret_cast<BucketT*>(reinterpret_cast<void*>(TmpStorage.buffer));
+ BucketT *TmpEnd = TmpBegin;
+
+ // Loop over the buckets, moving non-empty, non-tombstones into the
+@@ -940,17 +937,22 @@
+ // Note that this cast does not violate aliasing rules as we assert that
+ // the memory's dynamic type is the small, inline bucket buffer, and the
+ // 'storage.buffer' static type is 'char *'.
+- return reinterpret_cast<const BucketT *>(storage.buffer);
++ return reinterpret_cast<const BucketT*>(
++ reinterpret_cast<const void*>(storage.buffer));
+ }
++
+ BucketT *getInlineBuckets() {
+ return const_cast<BucketT *>(
+ const_cast<const SmallDenseMap *>(this)->getInlineBuckets());
+ }
++
+ const LargeRep *getLargeRep() const {
+ assert(!Small);
+ // Note, same rule about aliasing as with getInlineBuckets.
+- return reinterpret_cast<const LargeRep *>(storage.buffer);
++ return reinterpret_cast<const LargeRep*>(
++ reinterpret_cast<const void*>(storage.buffer));
+ }
++
+ LargeRep *getLargeRep() {
+ return const_cast<LargeRep *>(
+ const_cast<const SmallDenseMap *>(this)->getLargeRep());
+--- include/llvm/ADT/Optional.h 2014-09-30 19:12:35.000000000 -0700
++++ include/llvm/ADT/Optional.h 2015-12-07 14:59:03.998240128 -0800
+@@ -163,16 +163,34 @@
+ reset();
+ }
+
+- const T* getPointer() const { assert(hasVal); return reinterpret_cast<const T*>(storage.buffer); }
+- T* getPointer() { assert(hasVal); return reinterpret_cast<T*>(storage.buffer); }
+- const T& getValue() const LLVM_LVALUE_FUNCTION { assert(hasVal); return *getPointer(); }
++ const T* getPointer() const {
++ assert(hasVal);
++ return reinterpret_cast<const T*>(
++ reinterpret_cast<const void*>(storage.buffer));
++ }
++
++ T* getPointer() {
++ assert(hasVal);
++ return reinterpret_cast<T*>(
++ reinterpret_cast<void*>(storage.buffer));
++ }
++
++ const T& getValue() const LLVM_LVALUE_FUNCTION {
++ assert(hasVal);
++ return *getPointer();
++ }
++
+ T& getValue() LLVM_LVALUE_FUNCTION { assert(hasVal); return *getPointer(); }
+
+ LLVM_EXPLICIT operator bool() const { return hasVal; }
+ bool hasValue() const { return hasVal; }
+ const T* operator->() const { return getPointer(); }
+ T* operator->() { return getPointer(); }
+- const T& operator*() const LLVM_LVALUE_FUNCTION { assert(hasVal); return *getPointer(); }
++ const T& operator*() const LLVM_LVALUE_FUNCTION {
++ assert(hasVal);
++ return *getPointer();
++ }
++
+ T& operator*() LLVM_LVALUE_FUNCTION { assert(hasVal); return *getPointer(); }
+
+ template <typename U>
+--- include/llvm/ADT/ilist.h 2014-07-28 17:38:55.000000000 -0700
++++ include/llvm/ADT/ilist.h 2015-11-10 13:51:33.696789150 -0800
+@@ -104,6 +104,53 @@
+ }
+ };
+
++template <typename NodeTy> class ilist_half_node;
++template <typename NodeTy> class ilist_node;
++
++/// Traits with an embedded ilist_node as a sentinel.
++///
++/// FIXME: The downcast in createSentinel() is UB.
++template <typename NodeTy> struct ilist_embedded_sentinel_traits {
++ /// Get hold of the node that marks the end of the list.
++ NodeTy *createSentinel() const {
++ // Since i(p)lists always publicly derive from their corresponding traits,
++ // placing a data member in this class will augment the i(p)list. But since
++ // the NodeTy is expected to be publicly derive from ilist_node<NodeTy>,
++ // there is a legal viable downcast from it to NodeTy. We use this trick to
++ // superimpose an i(p)list with a "ghostly" NodeTy, which becomes the
++ // sentinel. Dereferencing the sentinel is forbidden (save the
++ // ilist_node<NodeTy>), so no one will ever notice the superposition.
++ return static_cast<NodeTy *>(&Sentinel);
++ }
++ static void destroySentinel(NodeTy *) {}
++
++ NodeTy *provideInitialHead() const { return createSentinel(); }
++ NodeTy *ensureHead(NodeTy *) const { return createSentinel(); }
++ static void noteHead(NodeTy *, NodeTy *) {}
++
++private:
++ mutable ilist_node<NodeTy> Sentinel;
++};
++
++/// Trait with an embedded ilist_half_node as a sentinel.
++///
++/// FIXME: The downcast in createSentinel() is UB.
++template <typename NodeTy> struct ilist_half_embedded_sentinel_traits {
++ /// Get hold of the node that marks the end of the list.
++ NodeTy *createSentinel() const {
++ // See comment in ilist_embedded_sentinel_traits::createSentinel().
++ return static_cast<NodeTy *>(&Sentinel);
++ }
++ static void destroySentinel(NodeTy *) {}
++
++ NodeTy *provideInitialHead() const { return createSentinel(); }
++ NodeTy *ensureHead(NodeTy *) const { return createSentinel(); }
++ static void noteHead(NodeTy *, NodeTy *) {}
++
++private:
++ mutable ilist_half_node<NodeTy> Sentinel;
++};
++
+ /// ilist_node_traits - A fragment for template traits for intrusive list
+ /// that provides default node related operations.
+ ///
+@@ -173,8 +220,8 @@
+ template<class T> void operator-(T) const;
+ public:
+
+- ilist_iterator(pointer NP) : NodePtr(NP) {}
+- ilist_iterator(reference NR) : NodePtr(&NR) {}
++ explicit ilist_iterator(pointer NP) : NodePtr(NP) {}
++ explicit ilist_iterator(reference NR) : NodePtr(&NR) {}
+ ilist_iterator() : NodePtr(nullptr) {}
+
+ // This is templated so that we can allow constructing a const iterator from
+@@ -191,8 +238,10 @@
+ return *this;
+ }
+
++ void reset(pointer NP) { NodePtr = NP; }
++
+ // Accessors...
+- operator pointer() const {
++ explicit operator pointer() const {
+ return NodePtr;
+ }
+
+@@ -237,14 +286,14 @@
+ // These are to catch errors when people try to use them as random access
+ // iterators.
+ template<typename T>
+-void operator-(int, ilist_iterator<T>) LLVM_DELETED_FUNCTION;
++void operator-(int, ilist_iterator<T>) = delete;
+ template<typename T>
+-void operator-(ilist_iterator<T>,int) LLVM_DELETED_FUNCTION;
++void operator-(ilist_iterator<T>,int) = delete;
+
+ template<typename T>
+-void operator+(int, ilist_iterator<T>) LLVM_DELETED_FUNCTION;
++void operator+(int, ilist_iterator<T>) = delete;
+ template<typename T>
+-void operator+(ilist_iterator<T>,int) LLVM_DELETED_FUNCTION;
++void operator+(ilist_iterator<T>,int) = delete;
+
+ // operator!=/operator== - Allow mixed comparisons without dereferencing
+ // the iterator, which could very likely be pointing to end().
+@@ -332,8 +381,8 @@
+
+ // No fundamental reason why iplist can't be copyable, but the default
+ // copy/copy-assign won't do.
+- iplist(const iplist &) LLVM_DELETED_FUNCTION;
+- void operator=(const iplist &) LLVM_DELETED_FUNCTION;
++ iplist(const iplist &) = delete;
++ void operator=(const iplist &) = delete;
+
+ public:
+ typedef NodeTy *pointer;
+@@ -422,7 +471,7 @@
+ this->setPrev(CurNode, New);
+
+ this->addNodeToList(New); // Notify traits that we added a node...
+- return New;
++ return iterator(New);
+ }
+
+ iterator insertAfter(iterator where, NodeTy *New) {
+@@ -443,7 +492,7 @@
+ else
+ Head = NextNode;
+ this->setPrev(NextNode, PrevNode);
+- IT = NextNode;
++ IT.reset(NextNode);
+ this->removeNodeFromList(Node); // Notify traits that we removed a node...
+
+ // Set the next/prev pointers of the current node to null. This isn't
+@@ -461,12 +510,18 @@
+ return remove(MutIt);
+ }
+
++ NodeTy *remove(NodeTy *IT) { return remove(iterator(IT)); }
++ NodeTy *remove(NodeTy &IT) { return remove(iterator(IT)); }
++
+ // erase - remove a node from the controlled sequence... and delete it.
+ iterator erase(iterator where) {
+ this->deleteNode(remove(where));
+ return where;
+ }
+
++ iterator erase(NodeTy *IT) { return erase(iterator(IT)); }
++ iterator erase(NodeTy &IT) { return erase(iterator(IT)); }
++
+ /// Remove all nodes from the list like clear(), but do not call
+ /// removeNodeFromList() or deleteNode().
+ ///
+@@ -522,7 +577,7 @@
+ this->setNext(Last, PosNext);
+ this->setPrev(PosNext, Last);
+
+- this->transferNodesFromList(L2, First, PosNext);
++ this->transferNodesFromList(L2, iterator(First), iterator(PosNext));
+
+ // Now that everything is set, restore the pointers to the list sentinels.
+ L2.setTail(L2Sentinel);
+@@ -579,6 +634,59 @@
+ void splice(iterator where, iplist &L2, iterator first, iterator last) {
+ if (first != last) transfer(where, L2, first, last);
+ }
++ void splice(iterator where, iplist &L2, NodeTy &N) {
++ splice(where, L2, iterator(N));
++ }
++ void splice(iterator where, iplist &L2, NodeTy *N) {
++ splice(where, L2, iterator(N));
++ }
++
++ template <class Compare>
++ void merge(iplist &Right, Compare comp) {
++ if (this == &Right)
++ return;
++ iterator First1 = begin(), Last1 = end();
++ iterator First2 = Right.begin(), Last2 = Right.end();
++ while (First1 != Last1 && First2 != Last2) {
++ if (comp(*First2, *First1)) {
++ iterator Next = First2;
++ transfer(First1, Right, First2, ++Next);
++ First2 = Next;
++ } else {
++ ++First1;
++ }
++ }
++ if (First2 != Last2)
++ transfer(Last1, Right, First2, Last2);
++ }
++ void merge(iplist &Right) { return merge(Right, op_less); }
++
++ template <class Compare>
++ void sort(Compare comp) {
++ // The list is empty, vacuously sorted.
++ if (empty())
++ return;
++ // The list has a single element, vacuously sorted.
++ if (std::next(begin()) == end())
++ return;
++ // Find the split point for the list.
++ iterator Center = begin(), End = begin();
++ while (End != end() && std::next(End) != end()) {
++ Center = std::next(Center);
++ End = std::next(std::next(End));
++ }
++ // Split the list into two.
++ iplist RightHalf;
++ RightHalf.splice(RightHalf.begin(), *this, Center, end());
++
++ // Sort the two sublists.
++ sort(comp);
++ RightHalf.sort(comp);
++
++ // Merge the two sublists back together.
++ merge(RightHalf, comp);
++ }
++ void sort() { sort(op_less); }
+ };
+
+
+--- include/llvm/ADT/ilist_node.h 2014-08-13 09:26:38.000000000 -0700
++++ include/llvm/ADT/ilist_node.h 2015-11-02 09:17:47.446456035 -0800
+@@ -19,12 +19,15 @@
+
+ template<typename NodeTy>
+ struct ilist_traits;
++template <typename NodeTy> struct ilist_embedded_sentinel_traits;
++template <typename NodeTy> struct ilist_half_embedded_sentinel_traits;
+
+ /// ilist_half_node - Base class that provides prev services for sentinels.
+ ///
+ template<typename NodeTy>
+ class ilist_half_node {
+ friend struct ilist_traits<NodeTy>;
++ friend struct ilist_half_embedded_sentinel_traits<NodeTy>;
+ NodeTy *Prev;
+ protected:
+ NodeTy *getPrev() { return Prev; }
+@@ -36,6 +39,8 @@
+ template<typename NodeTy>
+ struct ilist_nextprev_traits;
+
++template <typename NodeTy> class ilist_iterator;
++
+ /// ilist_node - Base class that provides next/prev services for nodes
+ /// that use ilist_nextprev_traits or ilist_default_traits.
+ ///
+@@ -43,6 +48,8 @@
+ class ilist_node : private ilist_half_node<NodeTy> {
+ friend struct ilist_nextprev_traits<NodeTy>;
+ friend struct ilist_traits<NodeTy>;
++ friend struct ilist_half_embedded_sentinel_traits<NodeTy>;
++ friend struct ilist_embedded_sentinel_traits<NodeTy>;
+ NodeTy *Next;
+ NodeTy *getNext() { return Next; }
+ const NodeTy *getNext() const { return Next; }
+@@ -51,6 +58,15 @@
+ ilist_node() : Next(nullptr) {}
+
+ public:
++ ilist_iterator<NodeTy> getIterator() {
++ // FIXME: Stop downcasting to create the iterator (potential UB).
++ return ilist_iterator<NodeTy>(static_cast<NodeTy *>(this));
++ }
++ ilist_iterator<const NodeTy> getIterator() const {
++ // FIXME: Stop downcasting to create the iterator (potential UB).
++ return ilist_iterator<const NodeTy>(static_cast<const NodeTy *>(this));
++ }
++
+ /// @name Adjacent Node Accessors
+ /// @{
+
+--- include/llvm/CodeGen/CommandFlags.h 2015-01-13 21:24:33.000000000 -0800
++++ include/llvm/CodeGen/CommandFlags.h 2016-01-26 14:46:39.000000000 -0800
+@@ -31,7 +31,7 @@
+ MCPU("mcpu",
+ cl::desc("Target a specific cpu type (-mcpu=help for details)"),
+ cl::value_desc("cpu-name"),
+- cl::init(""));
++ cl::init(std::string("")));
+
+ cl::list<std::string>
+ MAttrs("mattr",
+@@ -177,7 +177,7 @@
+ cl::opt<std::string>
+ TrapFuncName("trap-func", cl::Hidden,
+ cl::desc("Emit a call to trap function rather than a trap instruction"),
+- cl::init(""));
++ cl::init(std::string("")));
+
+ cl::opt<bool>
+ EnablePIE("enable-pie",
+@@ -192,11 +192,11 @@
+ cl::opt<std::string> StopAfter("stop-after",
+ cl::desc("Stop compilation after a specific pass"),
+ cl::value_desc("pass-name"),
+- cl::init(""));
++ cl::init(std::string("")));
+ cl::opt<std::string> StartAfter("start-after",
+ cl::desc("Resume compilation after a specific pass"),
+ cl::value_desc("pass-name"),
+- cl::init(""));
++ cl::init(std::string("")));
+
+ cl::opt<bool> DataSections("data-sections",
+ cl::desc("Emit data into separate sections"),
+@@ -258,7 +258,7 @@
+ // CFI.
+ cl::opt<std::string>
+ CFIFuncName("cfi-func-name", cl::desc("The name of the CFI function to call"),
+- cl::init(""));
++ cl::init(std::string("")));
+
+ // Common utility function tightly tied to the options listed here. Initializes
+ // a TargetOptions object with CodeGen flags and returns it.
+--- include/llvm/CodeGen/MachineBasicBlock.h 2014-11-13 16:34:59.000000000 -0800
++++ include/llvm/CodeGen/MachineBasicBlock.h 2015-12-06 12:31:19.423838338 -0800
+@@ -165,7 +165,7 @@
+ Ty &operator*() const { return *MII; }
+ Ty *operator->() const { return &operator*(); }
+
+- operator Ty*() const { return MII; }
++ operator Ty*() const { return MII.getNodePtrUnchecked(); }
+
+ bool operator==(const bundle_iterator &x) const {
+ return MII == x.MII;
+--- include/llvm/CodeGen/MachineFunction.h 2015-01-06 12:05:02.000000000 -0800
++++ include/llvm/CodeGen/MachineFunction.h 2015-12-06 20:18:16.623633498 -0800
+@@ -352,12 +352,10 @@
+ BasicBlocks.splice(InsertPt, BasicBlocks, MBBI, MBBE);
+ }
+
+- void remove(iterator MBBI) {
+- BasicBlocks.remove(MBBI);
+- }
+- void erase(iterator MBBI) {
+- BasicBlocks.erase(MBBI);
+- }
++ void remove(iterator MBBI) { BasicBlocks.remove(MBBI); }
++ void remove(MachineBasicBlock *MBBI) { BasicBlocks.remove(MBBI); }
++ void erase(iterator MBBI) { BasicBlocks.erase(MBBI); }
++ void erase(MachineBasicBlock *MBBI) { BasicBlocks.erase(MBBI); }
+
+ //===--------------------------------------------------------------------===//
+ // Internal functions used to automatically number MachineBasicBlocks
+--- include/llvm/CodeGen/MachineInstrBuilder.h 2014-10-31 16:19:46.000000000 -0700
++++ include/llvm/CodeGen/MachineInstrBuilder.h 2015-12-06 13:48:56.344154780 -0800
+@@ -280,7 +280,7 @@
+ const MCInstrDesc &MCID,
+ unsigned DestReg) {
+ if (I->isInsideBundle()) {
+- MachineBasicBlock::instr_iterator MII = I;
++ MachineBasicBlock::instr_iterator MII(I);
+ return BuildMI(BB, MII, DL, MCID, DestReg);
+ }
+
+@@ -317,7 +317,7 @@
+ DebugLoc DL,
+ const MCInstrDesc &MCID) {
+ if (I->isInsideBundle()) {
+- MachineBasicBlock::instr_iterator MII = I;
++ MachineBasicBlock::instr_iterator MII(I);
+ return BuildMI(BB, MII, DL, MCID);
+ }
+
+@@ -472,7 +472,7 @@
+ if (I == Begin) {
+ if (!empty())
+ MI->bundleWithSucc();
+- Begin = MI;
++ Begin = MI->getIterator();
+ return *this;
+ }
+ if (I == End) {
+--- include/llvm/CodeGen/MachineInstrBundle.h 2014-04-13 17:51:57.000000000 -0700
++++ include/llvm/CodeGen/MachineInstrBundle.h 2015-12-06 12:35:51.016366535 -0800
+@@ -44,23 +44,23 @@
+ /// getBundleStart - Returns the first instruction in the bundle containing MI.
+ ///
+ inline MachineInstr *getBundleStart(MachineInstr *MI) {
+- MachineBasicBlock::instr_iterator I = MI;
++ MachineBasicBlock::instr_iterator I(MI);
+ while (I->isBundledWithPred())
+ --I;
+- return I;
++ return &*I;
+ }
+
+ inline const MachineInstr *getBundleStart(const MachineInstr *MI) {
+- MachineBasicBlock::const_instr_iterator I = MI;
++ MachineBasicBlock::const_instr_iterator I(MI);
+ while (I->isBundledWithPred())
+ --I;
+- return I;
++ return &*I;
+ }
+
+ /// Return an iterator pointing beyond the bundle containing MI.
+ inline MachineBasicBlock::instr_iterator
+ getBundleEnd(MachineInstr *MI) {
+- MachineBasicBlock::instr_iterator I = MI;
++ MachineBasicBlock::instr_iterator I(MI);
+ while (I->isBundledWithSucc())
+ ++I;
+ return ++I;
+@@ -69,7 +69,7 @@
+ /// Return an iterator pointing beyond the bundle containing MI.
+ inline MachineBasicBlock::const_instr_iterator
+ getBundleEnd(const MachineInstr *MI) {
+- MachineBasicBlock::const_instr_iterator I = MI;
++ MachineBasicBlock::const_instr_iterator I(MI);
+ while (I->isBundledWithSucc())
+ ++I;
+ return ++I;
+@@ -116,10 +116,10 @@
+ ///
+ explicit MachineOperandIteratorBase(MachineInstr *MI, bool WholeBundle) {
+ if (WholeBundle) {
+- InstrI = getBundleStart(MI);
++ InstrI = getBundleStart(MI)->getIterator();
+ InstrE = MI->getParent()->instr_end();
+ } else {
+- InstrI = InstrE = MI;
++ InstrI = InstrE = MI->getIterator();
+ ++InstrE;
+ }
+ OpI = InstrI->operands_begin();
+--- include/llvm/CodeGen/SlotIndexes.h 2014-04-13 17:51:57.000000000 -0700
++++ include/llvm/CodeGen/SlotIndexes.h 2015-12-06 13:26:01.031361628 -0800
+@@ -427,11 +427,11 @@
+ /// Returns the next non-null index, if one exists.
+ /// Otherwise returns getLastIndex().
+ SlotIndex getNextNonNullIndex(SlotIndex Index) {
+- IndexList::iterator I = Index.listEntry();
++ IndexList::iterator I = Index.listEntry()->getIterator();
+ IndexList::iterator E = indexList.end();
+ while (++I != E)
+ if (I->getInstr())
+- return SlotIndex(I, Index.getSlot());
++ return SlotIndex(&*I, Index.getSlot());
+ // We reached the end of the function.
+ return getLastIndex();
+ }
+@@ -580,11 +580,11 @@
+ IndexList::iterator prevItr, nextItr;
+ if (Late) {
+ // Insert mi's index immediately before the following instruction.
+- nextItr = getIndexAfter(mi).listEntry();
++ nextItr = getIndexAfter(mi).listEntry()->getIterator();
+ prevItr = std::prev(nextItr);
+ } else {
+ // Insert mi's index immediately after the preceding instruction.
+- prevItr = getIndexBefore(mi).listEntry();
++ prevItr = getIndexBefore(mi).listEntry()->getIterator();
+ nextItr = std::next(prevItr);
+ }
+
+@@ -646,11 +646,11 @@
+ if (nextMBB == mbb->getParent()->end()) {
+ startEntry = &indexList.back();
+ endEntry = createEntry(nullptr, 0);
+- newItr = indexList.insertAfter(startEntry, endEntry);
++ newItr = indexList.insertAfter(startEntry->getIterator(), endEntry);
+ } else {
+ startEntry = createEntry(nullptr, 0);
+- endEntry = getMBBStartIdx(nextMBB).listEntry();
+- newItr = indexList.insert(endEntry, startEntry);
++ endEntry = getMBBStartIdx(&*nextMBB).listEntry();
++ newItr = indexList.insert(endEntry->getIterator(), startEntry);
+ }
+
+ SlotIndex startIdx(startEntry, SlotIndex::Slot_Block);
+--- include/llvm/IR/IRBuilder.h 2014-12-30 06:28:14.000000000 -0800
++++ include/llvm/IR/IRBuilder.h 2015-11-24 09:08:00.970126898 -0800
+@@ -58,9 +58,10 @@
+ FastMathFlags FMF;
+ public:
+
+- IRBuilderBase(LLVMContext &context, MDNode *FPMathTag = nullptr)
+- : Context(context), DefaultFPMathTag(FPMathTag), FMF() {
+- ClearInsertionPoint();
++ IRBuilderBase(LLVMContext &Ctx, MDNode *FPMathTag = nullptr)
++ : CurDbgLocation(), BB(nullptr), InsertPt(),
++ Context(Ctx), DefaultFPMathTag(FPMathTag), FMF() {
++ // ClearInsertionPoint();
+ }
+
+ //===--------------------------------------------------------------------===//
+@@ -71,7 +72,7 @@
+ /// inserted into a block.
+ void ClearInsertionPoint() {
+ BB = nullptr;
+- InsertPt = nullptr;
++ InsertPt.reset(nullptr);
+ }
+
+ BasicBlock *GetInsertBlock() const { return BB; }
+@@ -89,8 +90,8 @@
+ /// the specified instruction.
+ void SetInsertPoint(Instruction *I) {
+ BB = I->getParent();
+- InsertPt = I;
+- assert(I != BB->end() && "Can't read debug loc from end()");
++ InsertPt = I->getIterator();
++ assert(InsertPt != BB->end() && "Can't read debug loc from end()");
+ SetCurrentDebugLocation(I->getDebugLoc());
+ }
+
+@@ -99,6 +100,8 @@
+ void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
+ BB = TheBB;
+ InsertPt = IP;
++ if (IP != TheBB->end())
++ SetCurrentDebugLocation(IP->getDebugLoc());
+ }
+
+ /// \brief Find the nearest point that dominates this use, and specify that
+@@ -107,10 +110,12 @@
+ Instruction *UseInst = cast<Instruction>(U.getUser());
+ if (PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
+ BasicBlock *PredBB = Phi->getIncomingBlock(U);
+- assert(U != PredBB->getTerminator() && "critical edge not split");
+- SetInsertPoint(PredBB, PredBB->getTerminator());
++ TerminatorInst *TI = PredBB->getTerminator();
++ assert(U != TI && "critical edge not split");
++ SetInsertPoint(PredBB, TI->getIterator());
+ return;
+ }
++
+ SetInsertPoint(UseInst);
+ }
+
+--- include/llvm/IR/Metadata.h 2015-10-05 11:01:32.758196248 -0700
++++ include/llvm/IR/Metadata.h 2015-11-27 09:20:10.357775627 -0800
+@@ -927,6 +927,71 @@
+ using ReplaceableMetadataImpl::replaceAllUsesWith;
+ };
+
++template <class T>
++class TypedMDOperandIterator : public std::iterator<std::input_iterator_tag, T*, std::ptrdiff_t, void, T*> {
++private:
++ MDNode::op_iterator I = nullptr;
++
++public:
++ TypedMDOperandIterator() = default;
++ explicit TypedMDOperandIterator(MDNode::op_iterator I) : I(I) {}
++ ~TypedMDOperandIterator() { }
++
++ T *operator*() const { return cast_or_null<T>(*I); }
++
++ TypedMDOperandIterator &operator++() {
++ ++I;
++ return *this;
++ }
++
++ TypedMDOperandIterator operator++(int) {
++ TypedMDOperandIterator Temp(*this);
++ ++I;
++ return Temp;
++ }
++
++ bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
++ bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
++};
++
++template<class T> class MDTupleTypedArrayWrapper {
++private:
++ const MDTuple *N = nullptr;
++
++public:
++ MDTupleTypedArrayWrapper() = default;
++ MDTupleTypedArrayWrapper(const MDTuple *N) : N(N) {}
++ ~MDTupleTypedArrayWrapper() { }
++
++ template<class U>
++ MDTupleTypedArrayWrapper(const MDTupleTypedArrayWrapper<U> &Other,
++ typename std::enable_if<std::is_convertible<U*, T*>::value>::type* = nullptr)
++ : N(Other.get()) { }
++
++ template<class U>
++ explicit MDTupleTypedArrayWrapper(const MDTupleTypedArrayWrapper<U> &Other,
++ typename std::enable_if<!std::is_convertible<U*, T*>::value>::type* = nullptr)
++ : N(Other.get()) { }
++
++ explicit operator bool() const { return get(); }
++ explicit operator MDTuple *() const { return get(); }
++
++ MDTuple *get() const { return const_cast<MDTuple *>(N); }
++ MDTuple *operator->() const { return get(); }
++ MDTuple &operator*() const { return *get(); }
++
++ unsigned size() const { return N ? N->getNumOperands() : 0u; }
++ T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
++
++ typedef TypedMDOperandIterator<T> iterator;
++ iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
++ iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
++};
++
++#define HANDLE_METADATA(CLASS) \
++ typedef MDTupleTypedArrayWrapper<CLASS> CLASS##Array;
++#include "llvm/IR/Metadata.def"
++
+ //===----------------------------------------------------------------------===//
+ /// \brief A tuple of MDNodes.
+ ///
+--- include/llvm/MC/MCSection.h 2013-04-17 14:18:16.000000000 -0700
++++ include/llvm/MC/MCSection.h 2015-12-07 12:32:38.557027450 -0800
+@@ -15,6 +15,9 @@
+ #define LLVM_MC_MCSECTION_H
+
+ #include "llvm/ADT/StringRef.h"
++#include "llvm/ADT/ilist.h"
++#include "llvm/ADT/ilist_node.h"
++#include "llvm/MC/MCAssembler.h"
+ #include "llvm/MC/SectionKind.h"
+ #include "llvm/Support/Compiler.h"
+
+@@ -41,6 +44,14 @@
+ MCSection(SectionVariant V, SectionKind K) : Variant(V), Kind(K) {}
+ SectionVariant Variant;
+ SectionKind Kind;
++
++ public:
++ typedef iplist<MCFragment> FragmentListType;
++ typedef FragmentListType::const_iterator const_iterator;
++ typedef FragmentListType::iterator iterator;
++ typedef FragmentListType::const_reverse_iterator const_reverse_iterator;
++ typedef FragmentListType::reverse_iterator reverse_iterator;
++
+ public:
+ virtual ~MCSection();
+
+--- include/llvm/MC/MCTargetOptionsCommandFlags.h 2015-01-14 03:23:27.000000000 -0800
++++ include/llvm/MC/MCTargetOptionsCommandFlags.h 2016-01-26 19:29:37.000000000 -0800
+@@ -43,7 +43,7 @@
+ cl::opt<std::string>
+ ABIName("target-abi", cl::Hidden,
+ cl::desc("The name of the ABI to be targeted from the backend."),
+- cl::init(""));
++ cl::init(std::string("")));
+
+ static inline MCTargetOptions InitMCTargetOptionsFromFlags() {
+ MCTargetOptions Options;
+--- include/llvm/Support/GenericDomTree.h 2015-01-14 02:33:21.000000000 -0800
++++ include/llvm/Support/GenericDomTree.h 2015-12-08 09:12:30.450453075 -0800
+@@ -715,7 +715,11 @@
+ /// recalculate - compute a dominator tree for the given function
+ template <class FT> void recalculate(FT &F) {
+ typedef GraphTraits<FT *> TraitsTy;
++ typedef typename GraphTraits<FT*>::ChildIteratorType TraitsTyChildIterator;
++ typedef typename GraphTraits<FT*>::nodes_iterator TraitsTyNodeIterator;
++
+ reset();
++
+ this->Vertex.push_back(nullptr);
+
+ if (!this->IsPostDominators) {
+@@ -728,19 +732,22 @@
+ Calculate<FT, NodeT *>(*this, F);
+ } else {
+ // Initialize the roots list
+- for (typename TraitsTy::nodes_iterator I = TraitsTy::nodes_begin(&F),
+- E = TraitsTy::nodes_end(&F);
++ for (TraitsTyNodeIterator I = TraitsTy::nodes_begin(&F),
++ E = TraitsTy::nodes_end(&F);
+ I != E; ++I) {
+- if (TraitsTy::child_begin(I) == TraitsTy::child_end(I))
+- addRoot(I);
++ TraitsTyChildIterator ChildBegin(TraitsTy::child_begin(&*I));
++ TraitsTyChildIterator ChildEnd(TraitsTy::child_end(&*I));
++
++ if (ChildBegin == ChildEnd)
++ addRoot(&*I);
+
+ // Prepopulate maps so that we don't get iterator invalidation issues
+ // later.
+- this->IDoms[I] = nullptr;
+- this->DomTreeNodes[I] = nullptr;
++ this->IDoms[&*I] = nullptr;
++ this->DomTreeNodes[&*I] = nullptr;
+ }
+
+- Calculate<FT, Inverse<NodeT *>>(*this, F);
++ Calculate<FT, Inverse<NodeT*> >(*this, F);
+ }
+ }
+ };
+--- include/llvm/Transforms/Utils/SSAUpdaterImpl.h 2014-04-21 15:55:11.000000000 -0700
++++ include/llvm/Transforms/Utils/SSAUpdaterImpl.h 2015-11-29 13:46:28.070241785 -0800
+@@ -378,7 +378,7 @@
+ void FindExistingPHI(BlkT *BB, BlockListTy *BlockList) {
+ for (typename BlkT::iterator BBI = BB->begin(), BBE = BB->end();
+ BBI != BBE; ++BBI) {
+- PhiT *SomePHI = Traits::InstrIsPHI(BBI);
++ PhiT *SomePHI = Traits::InstrIsPHI(&*BBI);
+ if (!SomePHI)
+ break;
+ if (CheckIfPHIMatches(SomePHI)) {
+--- lib/Analysis/AliasAnalysisEvaluator.cpp 2014-07-24 05:16:19.000000000 -0700
++++ lib/Analysis/AliasAnalysisEvaluator.cpp 2015-11-27 17:10:53.853958210 -0800
+@@ -146,9 +146,9 @@
+ SetVector<Value *> Loads;
+ SetVector<Value *> Stores;
+
+- for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
+- if (I->getType()->isPointerTy()) // Add all pointer arguments.
+- Pointers.insert(I);
++ for (auto &I : F.args())
++ if (I.getType()->isPointerTy()) // Add all pointer arguments.
++ Pointers.insert(&I);
+
+ for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
+ if (I->getType()->isPointerTy()) // Add all pointer instructions.
+--- lib/Analysis/AliasAnalysis.cpp 2014-12-15 06:09:53.000000000 -0800
++++ lib/Analysis/AliasAnalysis.cpp 2015-11-27 09:33:58.058293495 -0800
+@@ -501,12 +501,12 @@
+ const ModRefResult Mode) {
+ assert(I1.getParent() == I2.getParent() &&
+ "Instructions not in same basic block!");
+- BasicBlock::const_iterator I = &I1;
+- BasicBlock::const_iterator E = &I2;
++ BasicBlock::const_iterator I = I1.getIterator();
++ BasicBlock::const_iterator E = I2.getIterator();
+ ++E; // Convert from inclusive to exclusive range.
+
+ for (; I != E; ++I) // Check every instruction in range
+- if (getModRefInfo(I, Loc) & Mode)
++ if (getModRefInfo(&(*I), Loc) & Mode)
+ return true;
+ return false;
+ }
+--- lib/Analysis/AliasSetTracker.cpp 2014-11-19 11:36:18.000000000 -0800
++++ lib/Analysis/AliasSetTracker.cpp 2015-11-27 09:52:20.756423865 -0800
+@@ -229,8 +229,8 @@
+ iterator Cur = I++;
+ if (Cur->Forward || !Cur->aliasesPointer(Ptr, Size, AAInfo, AA)) continue;
+
+- if (!FoundSet) { // If this is the first alias set ptr can go into.
+- FoundSet = Cur; // Remember it.
++ if (!FoundSet) { // If this is the first alias set ptr can go into.
++ FoundSet = &(*Cur); // Remember it.
+ } else { // Otherwise, we must merge the sets.
+ FoundSet->mergeSetIn(*Cur, *this); // Merge in contents.
+ }
+@@ -264,16 +264,13 @@
+ if (Cur->Forward || !Cur->aliasesUnknownInst(Inst, AA))
+ continue;
+ if (!FoundSet) // If this is the first alias set ptr can go into.
+- FoundSet = Cur; // Remember it.
++ FoundSet = &(*Cur); // Remember it.
+ else if (!Cur->Forward) // Otherwise, we must merge the sets.
+ FoundSet->mergeSetIn(*Cur, *this); // Merge in contents.
+ }
+ return FoundSet;
+ }
+
+-
+-
+-
+ /// getAliasSetForPointer - Return the alias set that the specified pointer
+ /// lives in.
+ AliasSet &AliasSetTracker::getAliasSetForPointer(Value *Pointer, uint64_t Size,
+@@ -287,13 +284,13 @@
+ // Return the set!
+ return *Entry.getAliasSet(*this)->getForwardedTarget(*this);
+ }
+-
++
+ if (AliasSet *AS = findAliasSetForPointer(Pointer, Size, AAInfo)) {
+ // Add it to the alias set it aliases.
+ AS->addPointer(*this, Entry, Size, AAInfo);
+ return *AS;
+ }
+-
++
+ if (New) *New = true;
+ // Otherwise create a new alias set to hold the loaded pointer.
+ AliasSets.push_back(new AliasSet());
+@@ -379,8 +376,8 @@
+ }
+
+ void AliasSetTracker::add(BasicBlock &BB) {
+- for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
+- add(I);
++ for (auto &I : BB)
++ add(&I);
+ }
+
+ void AliasSetTracker::add(const AliasSetTracker &AST) {
+--- lib/Analysis/BasicAliasAnalysis.cpp 2015-01-04 04:03:27.000000000 -0800
++++ lib/Analysis/BasicAliasAnalysis.cpp 2015-11-27 09:53:17.612141117 -0800
+@@ -1440,7 +1440,7 @@
+ // the Values cannot come from different iterations of a potential cycle the
+ // phi nodes could be involved in.
+ for (auto *P : VisitedPhiBBs)
+- if (isPotentiallyReachable(P->begin(), Inst, DT, LI))
++ if (isPotentiallyReachable(&P->front(), Inst, DT, LI))
+ return false;
+
+ return true;
+--- lib/Analysis/BlockFrequencyInfo.cpp 2014-06-26 15:52:05.000000000 -0700
++++ lib/Analysis/BlockFrequencyInfo.cpp 2015-11-27 09:55:32.251496178 -0800
+@@ -34,17 +34,17 @@
+ };
+
+ static cl::opt<GVDAGType>
+-ViewBlockFreqPropagationDAG("view-block-freq-propagation-dags", cl::Hidden,
+- cl::desc("Pop up a window to show a dag displaying how block "
+- "frequencies propagation through the CFG."),
+- cl::values(
+- clEnumValN(GVDT_None, "none",
+- "do not display graphs."),
+- clEnumValN(GVDT_Fraction, "fraction", "display a graph using the "
+- "fractional block frequency representation."),
+- clEnumValN(GVDT_Integer, "integer", "display a graph using the raw "
+- "integer fractional block frequency representation."),
+- clEnumValEnd));
++ViewBlockFreqPropagationDAG("view-block-freq-propagation-dags",
++ cl::Hidden,
++ cl::desc("Pop up a window to show a dag displaying how block "
++ "frequencies propagation through the CFG."),
++ cl::values(clEnumValN(GVDT_None, "none",
++ "do not display graphs."),
++ clEnumValN(GVDT_Fraction, "fraction", "display a graph using the "
++ "fractional block frequency representation."),
++ clEnumValN(GVDT_Integer, "integer", "display a graph using the raw "
++ "integer fractional block frequency representation."),
++ clEnumValEnd));
+
+ namespace llvm {
+
+@@ -55,8 +55,9 @@
+ typedef Function::const_iterator nodes_iterator;
+
+ static inline const NodeType *getEntryNode(const BlockFrequencyInfo *G) {
+- return G->getFunction()->begin();
++ return &(G->getFunction()->front());
+ }
++
+ static ChildIteratorType child_begin(const NodeType *N) {
+ return succ_begin(N);
+ }
+--- lib/Analysis/BranchProbabilityInfo.cpp 2014-12-09 10:38:53.000000000 -0800
++++ lib/Analysis/BranchProbabilityInfo.cpp 2015-11-27 09:59:58.010012465 -0800
+@@ -529,11 +529,10 @@
+ // We print the probabilities from the last function the analysis ran over,
+ // or the function it is currently running over.
+ assert(LastF && "Cannot print prior to running over a function");
+- for (Function::const_iterator BI = LastF->begin(), BE = LastF->end();
+- BI != BE; ++BI) {
+- for (succ_const_iterator SI = succ_begin(BI), SE = succ_end(BI);
++ for (const auto &BI : *LastF) {
++ for (succ_const_iterator SI = succ_begin(&BI), SE = succ_end(&BI);
+ SI != SE; ++SI) {
+- printEdgeProbability(OS << " ", BI, *SI);
++ printEdgeProbability(OS << " ", &BI, *SI);
+ }
+ }
+ }
+--- lib/Analysis/CFG.cpp 2015-01-12 19:46:47.000000000 -0800
++++ lib/Analysis/CFG.cpp 2015-11-27 10:13:16.659243122 -0800
+@@ -204,8 +204,9 @@
+ return true;
+
+ // Linear scan, start at 'A', see whether we hit 'B' or the end first.
+- for (BasicBlock::const_iterator I = A, E = BB->end(); I != E; ++I) {
+- if (&*I == B)
++ for (BasicBlock::const_iterator I = A->getIterator(), E = BB->end();
++ I != E; ++I) {
++ if (&(*I) == B)
+ return true;
+ }
+
+--- lib/Analysis/CodeMetrics.cpp 2015-01-04 04:03:27.000000000 -0800
++++ lib/Analysis/CodeMetrics.cpp 2015-11-27 10:14:02.544976823 -0800
+@@ -115,7 +115,7 @@
+ for (BasicBlock::const_iterator II = BB->begin(), E = BB->end();
+ II != E; ++II) {
+ // Skip ephemeral values.
+- if (EphValues.count(II))
++ if (EphValues.count(&(*II)))
+ continue;
+
+ // Special handling for calls.
+--- lib/Analysis/CostModel.cpp 2014-07-03 15:24:18.000000000 -0700
++++ lib/Analysis/CostModel.cpp 2015-11-27 10:20:35.600601500 -0800
+@@ -524,7 +524,7 @@
+
+ for (Function::iterator B = F->begin(), BE = F->end(); B != BE; ++B) {
+ for (BasicBlock::iterator it = B->begin(), e = B->end(); it != e; ++it) {
+- Instruction *Inst = it;
++ Instruction *Inst = &(*it);
+ unsigned Cost = getInstructionCost(Inst);
+ if (Cost != (unsigned)-1)
+ OS << "Cost Model: Found an estimated cost of " << Cost;
+--- lib/Analysis/IPA/CallGraph.cpp 2014-08-07 13:41:17.000000000 -0700
++++ lib/Analysis/IPA/CallGraph.cpp 2015-11-27 17:17:06.153920405 -0800
+@@ -25,7 +25,7 @@
+ CallsExternalNode(new CallGraphNode(nullptr)) {
+ // Add every function to the call graph.
+ for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
+- addToCallGraph(I);
++ addToCallGraph(&*I);
+
+ // If we didn't find a main function, use the external call graph node
+ if (!Root)
+--- lib/Analysis/IPA/GlobalsModRef.cpp 2014-05-08 10:57:50.000000000 -0700
++++ lib/Analysis/IPA/GlobalsModRef.cpp 2015-11-27 17:21:08.993461915 -0800
+@@ -209,9 +209,9 @@
+ std::vector<Function*> Readers, Writers;
+ for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
+ if (I->hasLocalLinkage()) {
+- if (!AnalyzeUsesOfPointer(I, Readers, Writers)) {
++ if (!AnalyzeUsesOfPointer(&*I, Readers, Writers)) {
+ // Remember that we are tracking this global.
+- NonAddressTakenGlobals.insert(I);
++ NonAddressTakenGlobals.insert(&*I);
+ ++NumNonAddrTakenFunctions;
+ }
+ Readers.clear(); Writers.clear();
+@@ -220,24 +220,26 @@
+ for (Module::global_iterator I = M.global_begin(), E = M.global_end();
+ I != E; ++I)
+ if (I->hasLocalLinkage()) {
+- if (!AnalyzeUsesOfPointer(I, Readers, Writers)) {
++ if (!AnalyzeUsesOfPointer(&*I, Readers, Writers)) {
+ // Remember that we are tracking this global, and the mod/ref fns
+- NonAddressTakenGlobals.insert(I);
++ NonAddressTakenGlobals.insert(&*I);
+
+ for (unsigned i = 0, e = Readers.size(); i != e; ++i)
+- FunctionInfo[Readers[i]].GlobalInfo[I] |= Ref;
++ FunctionInfo[Readers[i]].GlobalInfo[&*I] |= Ref;
+
+ if (!I->isConstant()) // No need to keep track of writers to constants
+ for (unsigned i = 0, e = Writers.size(); i != e; ++i)
+- FunctionInfo[Writers[i]].GlobalInfo[I] |= Mod;
++ FunctionInfo[Writers[i]].GlobalInfo[&*I] |= Mod;
+ ++NumNonAddrTakenGlobalVars;
+
+ // If this global holds a pointer type, see if it is an indirect global.
+ if (I->getType()->getElementType()->isPointerTy() &&
+- AnalyzeIndirectGlobalMemory(I))
++ AnalyzeIndirectGlobalMemory(&*I))
+ ++NumIndirectGlobalVars;
+ }
+- Readers.clear(); Writers.clear();
++
++ Readers.clear();
++ Writers.clear();
+ }
+ }
+
+--- lib/Analysis/IPA/InlineCost.cpp 2015-02-12 13:28:02.000000000 -0800
++++ lib/Analysis/IPA/InlineCost.cpp 2015-11-27 17:25:16.116008808 -0800
+@@ -900,7 +900,7 @@
+ continue;
+
+ // Skip ephemeral values.
+- if (EphValues.count(I))
++ if (EphValues.count(&*I))
+ continue;
+
+ ++NumInstructions;
+@@ -912,7 +912,7 @@
+ // all of the per-instruction logic. The visit tree returns true if we
+ // consumed the instruction in any way, and false if the instruction's base
+ // cost should count against inlining.
+- if (Base::visit(I))
++ if (Base::visit(&*I))
+ ++NumInstructionsSimplified;
+ else
+ Cost += InlineConstants::InstrCost;
+@@ -1089,15 +1089,15 @@
+ FAI != FAE; ++FAI, ++CAI) {
+ assert(CAI != CS.arg_end());
+ if (Constant *C = dyn_cast<Constant>(CAI))
+- SimplifiedValues[FAI] = C;
++ SimplifiedValues[&*FAI] = C;
+
+ Value *PtrArg = *CAI;
+ if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
+- ConstantOffsetPtrs[FAI] = std::make_pair(PtrArg, C->getValue());
++ ConstantOffsetPtrs[&*FAI] = std::make_pair(PtrArg, C->getValue());
+
+ // We can SROA any pointer arguments derived from alloca instructions.
+ if (isa<AllocaInst>(PtrArg)) {
+- SROAArgValues[FAI] = PtrArg;
++ SROAArgValues[&*FAI] = PtrArg;
+ SROAArgCosts[PtrArg] = 0;
+ }
+ }
+@@ -1334,9 +1334,8 @@
+ if (isa<IndirectBrInst>(BI->getTerminator()) || BI->hasAddressTaken())
+ return false;
+
+- for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE;
+- ++II) {
+- CallSite CS(II);
++ for (auto &II : *BI) {
++ CallSite CS(&II);
+ if (!CS)
+ continue;
+
+--- lib/Analysis/IVUsers.cpp 2014-11-18 23:49:26.000000000 -0800
++++ lib/Analysis/IVUsers.cpp 2015-11-27 10:24:31.961529730 -0800
+@@ -248,7 +248,6 @@
+ }
+
+ bool IVUsers::runOnLoop(Loop *l, LPPassManager &LPM) {
+-
+ L = l;
+ LI = &getAnalysis<LoopInfo>();
+ DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
+@@ -260,7 +259,7 @@
+ // them by stride. Start by finding all of the PHI nodes in the header for
+ // this loop. If they are induction variables, inspect their uses.
+ for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
+- (void)AddUsersIfInteresting(I);
++ (void) AddUsersIfInteresting(&(*I));
+
+ return false;
+ }
+--- lib/Analysis/Lint.cpp 2015-01-04 04:03:27.000000000 -0800
++++ lib/Analysis/Lint.cpp 2015-11-27 10:28:34.901567525 -0800
+@@ -231,7 +231,8 @@
+ for (; AI != AE; ++AI) {
+ Value *Actual = *AI;
+ if (PI != PE) {
+- Argument *Formal = PI++;
++ Argument *Formal = &(*PI);
++ PI++;
+ Assert1(Formal->getType() == Actual->getType(),
+ "Undefined behavior: Call argument type mismatches "
+ "callee parameter type", &I);
+@@ -609,8 +610,8 @@
+
+ void Lint::visitUnreachableInst(UnreachableInst &I) {
+ // This isn't undefined behavior, it's merely suspicious.
+- Assert1(&I == I.getParent()->begin() ||
+- std::prev(BasicBlock::iterator(&I))->mayHaveSideEffects(),
++ Assert1(&I == &(I.getParent()->front()) ||
++ std::prev(I.getIterator())->mayHaveSideEffects(),
+ "Unusual: unreachable immediately preceded by instruction without "
+ "side effects", &I);
+ }
+@@ -641,7 +642,7 @@
+ // TODO: Look through vector insert/extract/shuffle.
+ V = OffsetOk ? GetUnderlyingObject(V, DL) : V->stripPointerCasts();
+ if (LoadInst *L = dyn_cast<LoadInst>(V)) {
+- BasicBlock::iterator BBI = L;
++ BasicBlock::iterator BBI = L->getIterator();
+ BasicBlock *BB = L->getParent();
+ SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
+ for (;;) {
+--- lib/Analysis/Loads.cpp 2014-11-25 00:20:27.000000000 -0800
++++ lib/Analysis/Loads.cpp 2015-11-27 17:11:12.096570890 -0800
+@@ -110,7 +110,8 @@
+ // from/to. If so, the previous load or store would have already trapped,
+ // so there is no harm doing an extra load (also, CSE will later eliminate
+ // the load entirely).
+- BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
++ BasicBlock::iterator BBI = ScanFrom->getIterator();
++ BasicBlock::iterator E = ScanFrom->getParent()->begin();
+
+ // We can at least always strip pointer casts even though we can't use the
+ // base here.
+@@ -189,7 +190,8 @@
+ while (ScanFrom != ScanBB->begin()) {
+ // We must ignore debug info directives when counting (otherwise they
+ // would affect codegen).
+- Instruction *Inst = --ScanFrom;
++ --ScanFrom;
++ Instruction *Inst = &(*ScanFrom);
+ if (isa<DbgInfoIntrinsic>(Inst))
+ continue;
+
+--- lib/Analysis/MemoryBuiltins.cpp 2014-11-18 23:49:26.000000000 -0800
++++ lib/Analysis/MemoryBuiltins.cpp 2015-11-27 10:36:01.320964520 -0800
+@@ -642,7 +642,7 @@
+
+ // always generate code immediately before the instruction being
+ // processed, so that the generated code dominates the same BBs
+- Instruction *PrevInsertPoint = Builder.GetInsertPoint();
++ BuilderTy::InsertPointGuard Guard(Builder);
+ if (Instruction *I = dyn_cast<Instruction>(V))
+ Builder.SetInsertPoint(I);
+
+@@ -671,9 +671,6 @@
+ Result = unknown();
+ }
+
+- if (PrevInsertPoint)
+- Builder.SetInsertPoint(PrevInsertPoint);
+-
+ // Don't reuse CacheIt since it may be invalid at this point.
+ CacheMap[V] = Result;
+ return Result;
+@@ -763,7 +760,7 @@
+
+ // compute offset/size for each PHI incoming pointer
+ for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
+- Builder.SetInsertPoint(PHI.getIncomingBlock(i)->getFirstInsertionPt());
++ Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
+ SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
+
+ if (!bothKnown(EdgeData)) {
+--- lib/Analysis/MemoryDependenceAnalysis.cpp 2015-01-08 16:26:45.000000000 -0800
++++ lib/Analysis/MemoryDependenceAnalysis.cpp 2015-11-27 17:13:54.649752810 -0800
+@@ -215,7 +215,8 @@
+ if (!Limit)
+ return MemDepResult::getUnknown();
+
+- Instruction *Inst = --ScanIt;
++ --ScanIt;
++ Instruction *Inst = &(*ScanIt);
+
+ // If this inst is a memory op, get the pointer it accessed
+ AliasAnalysis::Location Loc;
+@@ -415,7 +416,8 @@
+
+ // Walk backwards through the basic block, looking for dependencies.
+ while (ScanIt != BB->begin()) {
+- Instruction *Inst = --ScanIt;
++ --ScanIt;
++ Instruction *Inst = &(*ScanIt);
+
+ if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
+ // Debug intrinsics don't (and can't) cause dependencies.
+@@ -676,12 +678,14 @@
+ if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(QueryInst))
+ isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_start;
+
+- LocalCache = getPointerDependencyFrom(MemLoc, isLoad, ScanPos,
++ LocalCache = getPointerDependencyFrom(MemLoc, isLoad,
++ ScanPos->getIterator(),
+ QueryParent, QueryInst);
+ } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
+ CallSite QueryCS(QueryInst);
+ bool isReadOnly = AA->onlyReadsMemory(QueryCS);
+- LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly, ScanPos,
++ LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly,
++ ScanPos->getIterator(),
+ QueryParent);
+ } else
+ // Non-memory instruction.
+@@ -805,7 +809,7 @@
+ BasicBlock::iterator ScanPos = DirtyBB->end();
+ if (ExistingResult) {
+ if (Instruction *Inst = ExistingResult->getResult().getInst()) {
+- ScanPos = Inst;
++ ScanPos = Inst->getIterator();
+ // We're removing QueryInst's use of Inst.
+ RemoveFromReverseMap(ReverseNonLocalDeps, Inst,
+ QueryCS.getInstruction());
+@@ -969,11 +973,11 @@
+ assert(ExistingResult->getResult().getInst()->getParent() == BB &&
+ "Instruction invalidated?");
+ ++NumCacheDirtyNonLocalPtr;
+- ScanPos = ExistingResult->getResult().getInst();
++ ScanPos = ExistingResult->getResult().getInst()->getIterator();
+
+ // Eliminating the dirty entry from 'Cache', so update the reverse info.
+ ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
+- RemoveFromReverseMap(ReverseNonLocalPtrDeps, ScanPos, CacheKey);
++ RemoveFromReverseMap(ReverseNonLocalPtrDeps, &(*ScanPos), CacheKey);
+ } else {
+ ++NumUncacheNonLocalPtr;
+ }
+@@ -1524,8 +1528,10 @@
+ // Using a dirty version of the instruction after RemInst saves having to scan
+ // the entire block to get to this point.
+ MemDepResult NewDirtyVal;
+- if (!RemInst->isTerminator())
+- NewDirtyVal = MemDepResult::getDirty(++BasicBlock::iterator(RemInst));
++ if (!RemInst->isTerminator()) {
++ ++RemInst;
++ NewDirtyVal = MemDepResult::getDirty(&*RemInst->getIterator());
++ }
+
+ ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
+ if (ReverseDepIt != ReverseLocalDeps.end()) {
+--- lib/Analysis/ScalarEvolutionExpander.cpp 2015-03-16 14:15:49.000000000 -0700
++++ lib/Analysis/ScalarEvolutionExpander.cpp 2015-11-27 17:14:51.881419145 -0800
+@@ -59,7 +59,7 @@
+ // Create a new cast, and leave the old cast in place in case
+ // it is being used as an insert point. Clear its operand
+ // so that it doesn't hold anything live.
+- Ret = CastInst::Create(Op, V, Ty, "", IP);
++ Ret = CastInst::Create(Op, V, Ty, "", &(*IP));
+ Ret->takeName(CI);
+ CI->replaceAllUsesWith(Ret);
+ CI->setOperand(0, UndefValue::get(V->getType()));
+@@ -71,12 +71,12 @@
+
+ // Create a new cast.
+ if (!Ret)
+- Ret = CastInst::Create(Op, V, Ty, V->getName(), IP);
++ Ret = CastInst::Create(Op, V, Ty, V->getName(), &(*IP));
+
+ // We assert at the end of the function since IP might point to an
+ // instruction with different dominance properties than a cast
+ // (an invoke for example) and not dominate BIP (but the cast does).
+- assert(SE.DT->dominates(Ret, BIP));
++ assert(SE.DT->dominates(Ret, &(*BIP)));
+
+ rememberInstruction(Ret);
+ return Ret;
+@@ -139,7 +139,8 @@
+
+ // Cast the instruction immediately after the instruction.
+ Instruction *I = cast<Instruction>(V);
+- BasicBlock::iterator IP = I; ++IP;
++ ++I;
++ BasicBlock::iterator IP = I->getIterator();
+ if (InvokeInst *II = dyn_cast<InvokeInst>(I))
+ IP = II->getNormalDest()->begin();
+ while (isa<PHINode>(IP) || isa<LandingPadInst>(IP))
+@@ -170,7 +171,7 @@
+ ScanLimit++;
+ if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
+ IP->getOperand(1) == RHS)
+- return IP;
++ return &(*IP);
+ if (IP == BlockBegin) break;
+ }
+ }
+@@ -186,7 +187,7 @@
+ if (!Preheader) break;
+
+ // Ok, move up a level.
+- Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
++ Builder.SetInsertPoint(Preheader->getTerminator());
+ }
+
+ // If we haven't found this binop, insert it.
+@@ -518,7 +519,8 @@
+ Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
+
+ assert(!isa<Instruction>(V) ||
+- SE.DT->dominates(cast<Instruction>(V), Builder.GetInsertPoint()));
++ SE.DT->dominates(cast<Instruction>(V),
++ &(*Builder.GetInsertPoint())));
+
+ // Expand the operands for a plain byte offset.
+ Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
+@@ -542,7 +544,7 @@
+ ScanLimit++;
+ if (IP->getOpcode() == Instruction::GetElementPtr &&
+ IP->getOperand(0) == V && IP->getOperand(1) == Idx)
+- return IP;
++ return &(*IP);
+ if (IP == BlockBegin) break;
+ }
+ }
+@@ -557,7 +559,7 @@
+ if (!Preheader) break;
+
+ // Ok, move up a level.
+- Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
++ Builder.SetInsertPoint(Preheader->getTerminator());
+ }
+
+ // Emit a GEP.
+@@ -588,7 +590,7 @@
+ if (!Preheader) break;
+
+ // Ok, move up a level.
+- Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
++ Builder.SetInsertPoint(Preheader->getTerminator());
+ }
+
+ // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
+@@ -1168,8 +1170,8 @@
+ PostIncLoops.clear();
+
+ // Expand code for the start value.
+- Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
+- L->getHeader()->begin());
++ Value *StartV =
++ expandCodeFor(Normalized->getStart(), ExpandTy, &(L->getHeader()->front()));
+
+ // StartV must be hoisted into L's preheader to dominate the new phi.
+ assert(!isa<Instruction>(StartV) ||
+@@ -1186,7 +1188,7 @@
+ if (useSubtract)
+ Step = SE.getNegativeSCEV(Step);
+ // Expand the step somewhere that dominates the loop header.
+- Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
++ Value *StepV = expandCodeFor(Step, IntTy, &(L->getHeader()->front()));
+
+ // Create the PHI.
+ BasicBlock *Header = L->getHeader();
+@@ -1297,7 +1299,7 @@
+ // or dominated by IVIncInsertPos.
+ if (isa<Instruction>(Result)
+ && !SE.DT->dominates(cast<Instruction>(Result),
+- Builder.GetInsertPoint())) {
++ &(*Builder.GetInsertPoint()))) {
+ // The induction variable's postinc expansion does not dominate this use.
+ // IVUsers tries to prevent this case, so it is rare. However, it can
+ // happen when an IVUser outside the loop is not dominated by the latch
+@@ -1315,8 +1317,9 @@
+ {
+ // Expand the step somewhere that dominates the loop header.
+ BuilderType::InsertPointGuard Guard(Builder);
+- StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
++ StepV = expandCodeFor(Step, IntTy, &(L->getHeader()->front()));
+ }
++
+ Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
+ }
+ }
+@@ -1395,7 +1398,7 @@
+ isa<LandingPadInst>(NewInsertPt))
+ ++NewInsertPt;
+ V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
+- NewInsertPt);
++ &(*NewInsertPt));
+ return V;
+ }
+
+@@ -1436,7 +1439,7 @@
+ BasicBlock *Header = L->getHeader();
+ pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
+ CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
+- Header->begin());
++ &(Header->front()));
+ rememberInstruction(CanonicalIV);
+
+ SmallSet<BasicBlock *, 4> PredSeen;
+@@ -1581,7 +1584,8 @@
+
+ Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
+ Instruction *IP) {
+- Builder.SetInsertPoint(IP->getParent(), IP);
++ assert(IP && "Invalid Instruction argument!");
++ Builder.SetInsertPoint(IP);
+ return expandCodeFor(SH, Ty);
+ }
+
+@@ -1599,7 +1603,7 @@
+ Value *SCEVExpander::expand(const SCEV *S) {
+ // Compute an insertion point for this SCEV object. Hoist the instructions
+ // as far out in the loop nest as possible.
+- Instruction *InsertPt = Builder.GetInsertPoint();
++ Instruction *InsertPt = &(*Builder.GetInsertPoint());
+ for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
+ L = L->getParentLoop())
+ if (SE.isLoopInvariant(S, L)) {
+@@ -1610,18 +1614,18 @@
+ // LSR sets the insertion point for AddRec start/step values to the
+ // block start to simplify value reuse, even though it's an invalid
+ // position. SCEVExpander must correct for this in all cases.
+- InsertPt = L->getHeader()->getFirstInsertionPt();
++ InsertPt = &*L->getHeader()->getFirstInsertionPt();
+ }
+ } else {
+ // If the SCEV is computable at this level, insert it into the header
+ // after the PHIs (and after any other instructions that we've inserted
+ // there) so that it is guaranteed to dominate any user inside the loop.
+ if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
+- InsertPt = L->getHeader()->getFirstInsertionPt();
++ InsertPt = &*L->getHeader()->getFirstInsertionPt();
+ while (InsertPt != Builder.GetInsertPoint()
+ && (isInsertedInstruction(InsertPt)
+ || isa<DbgInfoIntrinsic>(InsertPt))) {
+- InsertPt = std::next(BasicBlock::iterator(InsertPt));
++ InsertPt = &(*std::next(BasicBlock::iterator(InsertPt)));
+ }
+ break;
+ }
+@@ -1633,7 +1637,7 @@
+ return I->second;
+
+ BuilderType::InsertPointGuard Guard(Builder);
+- Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
++ Builder.SetInsertPoint(InsertPt);
+
+ // Expand the expression into instructions.
+ Value *V = visit(S);
+@@ -1671,8 +1675,9 @@
+
+ // Emit code for it.
+ BuilderType::InsertPointGuard Guard(Builder);
+- PHINode *V = cast<PHINode>(expandCodeFor(H, nullptr,
+- L->getHeader()->begin()));
++ PHINode *V =
++ cast<PHINode>(expandCodeFor(H, nullptr,
++ &(L->getHeader()->front())));
+
+ return V;
+ }
+@@ -1778,7 +1783,7 @@
+ if (OrigInc->getType() != IsomorphicInc->getType()) {
+ Instruction *IP = nullptr;
+ if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
+- IP = PN->getParent()->getFirstInsertionPt();
++ IP = &*PN->getParent()->getFirstInsertionPt();
+ else
+ IP = OrigInc->getNextNode();
+
+@@ -1796,7 +1801,7 @@
+ ++NumElim;
+ Value *NewIV = OrigPhiRef;
+ if (OrigPhiRef->getType() != Phi->getType()) {
+- IRBuilder<> Builder(L->getHeader()->getFirstInsertionPt());
++ IRBuilder<> Builder(&*L->getHeader()->getFirstInsertionPt());
+ Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
+ NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
+ }
+--- lib/Analysis/ScalarEvolutionNormalization.cpp 2014-08-29 14:53:01.000000000 -0700
++++ lib/Analysis/ScalarEvolutionNormalization.cpp 2015-11-27 15:32:52.251292445 -0800
+@@ -109,7 +109,7 @@
+ SmallVector<const SCEV *, 8> Operands;
+ const Loop *L = AR->getLoop();
+ // The addrec conceptually uses its operands at loop entry.
+- Instruction *LUser = L->getHeader()->begin();
++ Instruction *LUser = &(L->getHeader()->front());
+ // Transform each operand.
+ for (SCEVNAryExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
+ I != E; ++I) {
+--- lib/Analysis/SparsePropagation.cpp 2014-04-21 19:48:03.000000000 -0700
++++ lib/Analysis/SparsePropagation.cpp 2015-11-27 16:56:54.595156233 -0800
+@@ -328,17 +328,17 @@
+
+ void SparseSolver::Print(Function &F, raw_ostream &OS) const {
+ OS << "\nFUNCTION: " << F.getName() << "\n";
+- for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
+- if (!BBExecutable.count(BB))
++ for (auto &BB : F) {
++ if (!BBExecutable.count(&BB))
+ OS << "INFEASIBLE: ";
+ OS << "\t";
+- if (BB->hasName())
+- OS << BB->getName() << ":\n";
++ if (BB.hasName())
++ OS << BB.getName() << ":\n";
+ else
+ OS << "; anon bb\n";
+- for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
+- LatticeFunc->PrintValue(getLatticeState(I), OS);
+- OS << *I << "\n";
++ for (auto &I : BB) {
++ LatticeFunc->PrintValue(getLatticeState(&I), OS);
++ OS << I << "\n";
+ }
+
+ OS << "\n";
+--- lib/Analysis/ValueTracking.cpp 2015-01-14 03:23:27.000000000 -0800
++++ lib/Analysis/ValueTracking.cpp 2015-11-27 17:02:21.643435710 -0800
+@@ -403,8 +403,8 @@
+ for (BasicBlock::const_iterator I =
+ std::next(BasicBlock::const_iterator(Q.CxtI)),
+ IE(Inv); I != IE; ++I)
+- if (!isSafeToSpeculativelyExecute(I, DL) &&
+- !isAssumeLikeIntrinsic(I))
++ if (!isSafeToSpeculativelyExecute(&*I, DL) &&
++ !isAssumeLikeIntrinsic(&*I))
+ return false;
+
+ return !isEphemeralValueOf(Inv, Q.CxtI);
+@@ -421,15 +421,15 @@
+ // of the block); the common case is that the assume will come first.
+ for (BasicBlock::iterator I = std::next(BasicBlock::iterator(Inv)),
+ IE = Inv->getParent()->end(); I != IE; ++I)
+- if (I == Q.CxtI)
++ if (&*I == Q.CxtI)
+ return true;
+
+ // The context must come first...
+ for (BasicBlock::const_iterator I =
+ std::next(BasicBlock::const_iterator(Q.CxtI)),
+ IE(Inv); I != IE; ++I)
+- if (!isSafeToSpeculativelyExecute(I, DL) &&
+- !isAssumeLikeIntrinsic(I))
++ if (!isSafeToSpeculativelyExecute(&*I, DL) &&
++ !isAssumeLikeIntrinsic(&*I))
+ return false;
+
+ return !isEphemeralValueOf(Inv, Q.CxtI);
+--- lib/AsmParser/LLParser.cpp 2015-01-13 13:10:44.000000000 -0800
++++ lib/AsmParser/LLParser.cpp 2015-12-06 12:01:01.192696877 -0800
+@@ -152,8 +152,10 @@
+ U->resolveCycles();
+
+ // Look for intrinsic functions and CallInst that need to be upgraded
+- for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
+- UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
++ for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
++ UpgradeCallsToIntrinsic(&*FI); // must be post-increment, as we remove
++ ++FI;
++ }
+
+ UpgradeDebugInfo(*M);
+
+@@ -2091,7 +2093,7 @@
+ for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
+ AI != E; ++AI)
+ if (!AI->hasName())
+- NumberedVals.push_back(AI);
++ NumberedVals.push_back(&*AI);
+ }
+
+ LLParser::PerFunctionState::~PerFunctionState() {
+--- lib/Bitcode/Reader/BitcodeReader.cpp 2015-02-17 13:27:11.000000000 -0800
++++ lib/Bitcode/Reader/BitcodeReader.cpp 2015-12-06 12:21:14.006297865 -0800
+@@ -1830,7 +1830,7 @@
+ return Error("Invalid ID");
+ ++BBI;
+ }
+- BB = BBI;
++ BB = &*BBI;
+ } else {
+ // Otherwise insert a placeholder and remember it so it can be inserted
+ // when the function is parsed.
+@@ -1945,20 +1945,15 @@
+ return Error("Malformed global initializer set");
+
+ // Look for intrinsic functions which need to be upgraded at some point
+- for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
+- FI != FE; ++FI) {
++ for (Function &F : *TheModule) {
+ Function *NewFn;
+- if (UpgradeIntrinsicFunction(FI, NewFn))
+- UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
++ if (UpgradeIntrinsicFunction(&F, NewFn))
++ UpgradedIntrinsics.push_back(std::make_pair(&F, NewFn));
+ }
+
+ // Look for global variables which need to be renamed.
+- for (Module::global_iterator
+- GI = TheModule->global_begin(), GE = TheModule->global_end();
+- GI != GE;) {
+- GlobalVariable *GV = GI++;
+- UpgradeGlobalVariable(GV);
+- }
++ for (GlobalVariable &GV : TheModule->globals())
++ UpgradeGlobalVariable(&GV);
+
+ // Force deallocation of memory for these vectors to favor the client that
+ // want lazy deserialization.
+@@ -2528,8 +2523,8 @@
+ unsigned ModuleMDValueListSize = MDValueList.size();
+
+ // Add all the function arguments to the value table.
+- for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
+- ValueList.push_back(I);
++ for (Argument &I : F->args())
++ ValueList.push_back(&I);
+
+ unsigned NextValueNo = ValueList.size();
+ BasicBlock *CurBB = nullptr;
+@@ -3555,9 +3550,8 @@
+
+ // Iterate over the module, deserializing any functions that are still on
+ // disk.
+- for (Module::iterator F = TheModule->begin(), E = TheModule->end();
+- F != E; ++F) {
+- if (std::error_code EC = materialize(F))
++ for (Function &F : *TheModule) {
++ if (std::error_code EC = materialize(&F))
+ return EC;
+ }
+ // At this point, if there are any function bodies, the current bit is
+--- lib/Bitcode/Writer/BitcodeWriter.cpp 2015-01-13 13:10:44.000000000 -0800
++++ lib/Bitcode/Writer/BitcodeWriter.cpp 2015-12-06 12:22:42.877667625 -0800
+@@ -924,7 +924,7 @@
+ // If no metadata, ignore instruction.
+ if (MDs.empty()) continue;
+
+- Record.push_back(VE.getInstructionID(I));
++ Record.push_back(VE.getInstructionID(&*I));
+
+ for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
+ Record.push_back(MDs[i].first);
+--- lib/Bitcode/Writer/ValueEnumerator.cpp 2015-01-13 13:10:44.000000000 -0800
++++ lib/Bitcode/Writer/ValueEnumerator.cpp 2015-12-06 12:26:51.090576745 -0800
+@@ -290,18 +290,18 @@
+ // Enumerate the global variables.
+ for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
+ I != E; ++I)
+- EnumerateValue(I);
++ EnumerateValue(&*I);
+
+ // Enumerate the functions.
+ for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
+- EnumerateValue(I);
++ EnumerateValue(&*I);
+ EnumerateAttributes(cast<Function>(I)->getAttributes());
+ }
+
+ // Enumerate the aliases.
+ for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
+ I != E; ++I)
+- EnumerateValue(I);
++ EnumerateValue(&*I);
+
+ // Remember what is the cutoff between globalvalue's and other constants.
+ unsigned FirstConstant = Values.size();
+@@ -509,7 +509,7 @@
+ for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
+ E = M.named_metadata_end();
+ I != E; ++I)
+- EnumerateNamedMDNode(I);
++ EnumerateNamedMDNode(&*I);
+ }
+
+ void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
+@@ -726,7 +726,7 @@
+ // Adding function arguments to the value table.
+ for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
+ I != E; ++I)
+- EnumerateValue(I);
++ EnumerateValue(&*I);
+
+ FirstFuncConstantID = Values.size();
+
+@@ -739,8 +739,8 @@
+ isa<InlineAsm>(*OI))
+ EnumerateValue(*OI);
+ }
+- BasicBlocks.push_back(BB);
+- ValueMap[BB] = BasicBlocks.size();
++ BasicBlocks.push_back(&*BB);
++ ValueMap[&*BB] = BasicBlocks.size();
+ }
+
+ // Optimize the constant layout.
+@@ -765,7 +765,7 @@
+ }
+
+ if (!I->getType()->isVoidTy())
+- EnumerateValue(I);
++ EnumerateValue(&*I);
+ }
+ }
+
+@@ -793,7 +793,7 @@
+ DenseMap<const BasicBlock*, unsigned> &IDMap) {
+ unsigned Counter = 0;
+ for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
+- IDMap[BB] = ++Counter;
++ IDMap[&*BB] = ++Counter;
+ }
+
+ /// getGlobalBasicBlockID - This returns the function-specific ID for the
+--- lib/CodeGen/Analysis.cpp 2015-06-12 08:57:35.000000000 -0700
++++ lib/CodeGen/Analysis.cpp 2015-12-06 12:38:15.443685028 -0800
+@@ -514,7 +514,7 @@
+ if (isa<DbgInfoIntrinsic>(BBI))
+ continue;
+ if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
+- !isSafeToSpeculativelyExecute(BBI))
++ !isSafeToSpeculativelyExecute(&*BBI))
+ return false;
+ }
+
+--- lib/CodeGen/AsmPrinter/AsmPrinter.cpp 2015-01-12 16:48:10.000000000 -0800
++++ lib/CodeGen/AsmPrinter/AsmPrinter.cpp 2016-01-21 10:23:14.978051692 -0800
+@@ -857,6 +857,7 @@
+ MCSymbol *Sym = GetBlockAddressSymbol(&BB);
+ if (Sym->isDefined())
+ continue;
++
+ OutStreamer.AddComment("Address of block that was removed by CodeGen");
+ OutStreamer.EmitLabel(Sym);
+ }
+@@ -864,8 +865,8 @@
+ // Emit target-specific gunk after the function body.
+ EmitFunctionBodyEnd();
+
+- // If the target wants a .size directive for the size of the function, emit
+- // it.
++ // If the target wants a .size directive for the size of the function,
++ // emit it.
+ if (MAI->hasDotTypeDotSizeDirective()) {
+ // Create a symbol for the end of function, so we can get the size as
+ // difference between the function label and the temp label.
+@@ -885,6 +886,7 @@
+ NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
+ HI.Handler->endFunction(MF);
+ }
++
+ MMI->EndFunction();
+
+ // Print out jump tables referenced by the function.
+--- lib/CodeGen/AtomicExpandPass.cpp 2014-09-25 10:27:43.000000000 -0700
++++ lib/CodeGen/AtomicExpandPass.cpp 2015-12-06 12:41:26.021558967 -0800
+@@ -298,7 +298,8 @@
+ // atomicrmw.end:
+ // fence?
+ // [...]
+- BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
++ BasicBlock *ExitBB = BB->splitBasicBlock(AI->getIterator(),
++ "atomicrmw.end");
+ BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
+
+ // This grabs the DebugLoc from AI.
+@@ -355,7 +356,7 @@
+ // br i1 %success, label %atomicrmw.end, label %loop
+ // atomicrmw.end:
+ // [...]
+- BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
++ BasicBlock *ExitBB = BB->splitBasicBlock(AI->getIterator(), "atomicrmw.end");
+ BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
+
+ // This grabs the DebugLoc from AI.
+@@ -436,7 +437,7 @@
+ // %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
+ // %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
+ // [...]
+- BasicBlock *ExitBB = BB->splitBasicBlock(CI, "cmpxchg.end");
++ BasicBlock *ExitBB = BB->splitBasicBlock(CI->getIterator(), "cmpxchg.end");
+ auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
+ auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, FailureBB);
+ auto TryStoreBB = BasicBlock::Create(Ctx, "cmpxchg.trystore", F, SuccessBB);
+--- lib/CodeGen/BasicTargetTransformInfo.cpp 2015-01-07 16:51:32.000000000 -0800
++++ lib/CodeGen/BasicTargetTransformInfo.cpp 2015-12-06 12:42:25.950965490 -0800
+@@ -240,7 +240,7 @@
+
+ for (BasicBlock::iterator J = BB->begin(), JE = BB->end(); J != JE; ++J)
+ if (isa<CallInst>(J) || isa<InvokeInst>(J)) {
+- ImmutableCallSite CS(J);
++ ImmutableCallSite CS(&*J);
+ if (const Function *F = CS.getCalledFunction()) {
+ if (!TopTTI->isLoweredToCall(F))
+ continue;
+--- lib/CodeGen/BranchFolding.cpp 2014-11-18 23:49:26.000000000 -0800
++++ lib/CodeGen/BranchFolding.cpp 2015-12-06 14:41:40.491854005 -0800
+@@ -130,7 +130,7 @@
+ TriedMerging.erase(MBB);
+
+ // Remove the block.
+- MF->erase(MBB);
++ MF->erase(MBB->getIterator());
+ }
+
+ /// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
+@@ -207,12 +207,12 @@
+
+ // Fix CFG. The later algorithms expect it to be right.
+ bool MadeChange = false;
+- for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
+- MachineBasicBlock *MBB = I, *TBB = nullptr, *FBB = nullptr;
++ for (MachineBasicBlock &MBB : MF) {
++ MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
+ SmallVector<MachineOperand, 4> Cond;
+- if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true))
+- MadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
+- MadeChange |= OptimizeImpDefsBlock(MBB);
++ if (!TII->AnalyzeBranch(MBB, TBB, FBB, Cond, true))
++ MadeChange |= MBB.CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
++ MadeChange |= OptimizeImpDefsBlock(&MBB);
+ }
+
+ bool MadeChangeThisIteration = true;
+@@ -426,7 +426,7 @@
+ MachineFunction &MF = *CurMBB.getParent();
+
+ // Create the fall-through block.
+- MachineFunction::iterator MBBI = &CurMBB;
++ MachineFunction::iterator MBBI = CurMBB.getIterator();
+ MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(BB);
+ CurMBB.getParent()->insert(++MBBI, NewMBB);
+
+@@ -479,7 +479,7 @@
+ DebugLoc dl; // FIXME: this is nowhere
+ if (I != MF->end() &&
+ !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
+- MachineBasicBlock *NextBB = I;
++ MachineBasicBlock *NextBB = &*I;
+ if (TBB == NextBB && !Cond.empty() && !FBB) {
+ if (!TII->ReverseBranchCondition(Cond)) {
+ TII->RemoveBranch(*CurMBB);
+@@ -785,8 +785,8 @@
+ // block, which we can't jump to), we can treat all blocks with this same
+ // tail at once. Use PredBB if that is one of the possibilities, as that
+ // will not introduce any extra branches.
+- MachineBasicBlock *EntryBB = MergePotentials.begin()->getBlock()->
+- getParent()->begin();
++ MachineBasicBlock *EntryBB =
++ &MergePotentials.front().getBlock()->getParent()->front();
+ unsigned commonTailIndex = SameTails.size();
+ // If there are two blocks, check to see if one can be made to fall through
+ // into the other.
+@@ -860,12 +860,12 @@
+
+ // First find blocks with no successors.
+ MergePotentials.clear();
+- for (MachineFunction::iterator I = MF.begin(), E = MF.end();
+- I != E && MergePotentials.size() < TailMergeThreshold; ++I) {
+- if (TriedMerging.count(I))
+- continue;
+- if (I->succ_empty())
+- MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(I), I));
++ for (MachineBasicBlock &MBB : MF) {
++ if (MergePotentials.size() == TailMergeThreshold)
++ break;
++
++ if (!TriedMerging.count(&MBB) && MBB.succ_empty())
++ MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(&MBB), &MBB));
+ }
+
+ // If this is a large problem, avoid visiting the same basic blocks
+@@ -901,8 +901,8 @@
+ I != E; ++I) {
+ if (I->pred_size() < 2) continue;
+ SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
+- MachineBasicBlock *IBB = I;
+- MachineBasicBlock *PredBB = std::prev(I);
++ MachineBasicBlock *IBB = &*I;
++ MachineBasicBlock *PredBB = &*std::prev(I);
+ MergePotentials.clear();
+ for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
+ E2 = I->pred_end();
+@@ -933,18 +933,21 @@
+ if (TII->ReverseBranchCondition(NewCond))
+ continue;
+ // This is the QBB case described above
+- if (!FBB)
+- FBB = std::next(MachineFunction::iterator(PBB));
++ if (!FBB) {
++ auto Next = ++PBB->getIterator();
++ if (Next != MF.end())
++ FBB = &*Next;
++ }
+ }
+
+ // Failing case: the only way IBB can be reached from PBB is via
+ // exception handling. Happens for landing pads. Would be nice to have
+ // a bit in the edge so we didn't have to do all this.
+ if (IBB->isLandingPad()) {
+- MachineFunction::iterator IP = PBB; IP++;
++ MachineFunction::iterator IP = ++PBB->getIterator();
+ MachineBasicBlock *PredNextBB = nullptr;
+ if (IP != MF.end())
+- PredNextBB = IP;
++ PredNextBB = &*IP;
+ if (!TBB) {
+ if (IBB != PredNextBB) // fallthrough
+ continue;
+@@ -985,7 +988,7 @@
+
+ // Reinsert an unconditional branch if needed. The 1 below can occur as a
+ // result of removing blocks in TryTailMergeBlocks.
+- PredBB = std::prev(I); // this may have been changed in TryTailMergeBlocks
++ PredBB = &*std::prev(I); // this may have been changed in TryTailMergeBlocks
+ if (MergePotentials.size() == 1 &&
+ MergePotentials.begin()->getBlock() != PredBB)
+ FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
+@@ -1044,7 +1047,7 @@
+
+ for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
+ I != E; ) {
+- MachineBasicBlock *MBB = I++;
++ MachineBasicBlock *MBB = &*I++;
+ MadeChange |= OptimizeBlock(MBB);
+
+ // If it is dead, remove it.
+@@ -1132,7 +1135,7 @@
+ MachineFunction &MF = *MBB->getParent();
+ ReoptimizeBlock:
+
+- MachineFunction::iterator FallThrough = MBB;
++ MachineFunction::iterator FallThrough = MBB->getIterator();
+ ++FallThrough;
+
+ // If this block is empty, make everyone use its fall-through, not the block
+@@ -1150,12 +1153,12 @@
+ // instead.
+ while (!MBB->pred_empty()) {
+ MachineBasicBlock *Pred = *(MBB->pred_end()-1);
+- Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
++ Pred->ReplaceUsesOfBlockWith(MBB, &*FallThrough);
+ }
+ // If MBB was the target of a jump table, update jump tables to go to the
+ // fallthrough instead.
+ if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
+- MJTI->ReplaceMBBInJumpTables(MBB, FallThrough);
++ MJTI->ReplaceMBBInJumpTables(MBB, &*FallThrough);
+ MadeChange = true;
+ }
+ return MadeChange;
+@@ -1293,7 +1296,7 @@
+ TII->InsertBranch(PrevBB, MBB, nullptr, NewPriorCond, dl);
+
+ // Move this block to the end of the function.
+- MBB->moveAfter(--MF.end());
++ MBB->moveAfter(&MF.back());
+ MadeChange = true;
+ ++NumBranchOpts;
+ return MadeChange;
+@@ -1440,11 +1443,8 @@
+ if (!MBB->isLandingPad()) {
+ // Check all the predecessors of this block. If one of them has no fall
+ // throughs, move this block right after it.
+- for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
+- E = MBB->pred_end(); PI != E; ++PI) {
++ for (MachineBasicBlock *PredBB : MBB->predecessors()) {
+ // Analyze the branch at the end of the pred.
+- MachineBasicBlock *PredBB = *PI;
+- MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
+ MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
+ SmallVector<MachineOperand, 4> PredCond;
+ if (PredBB != MBB && !PredBB->canFallThrough() &&
+@@ -1462,8 +1462,7 @@
+ // B elsewhere
+ // next:
+ if (CurFallsThru) {
+- MachineBasicBlock *NextBB =
+- std::next(MachineFunction::iterator(MBB));
++ MachineBasicBlock *NextBB = &*std::next(MBB->getIterator());
+ CurCond.clear();
+ TII->InsertBranch(*MBB, NextBB, nullptr, CurCond, DebugLoc());
+ }
+@@ -1476,11 +1475,13 @@
+
+ if (!CurFallsThru) {
+ // Check all successors to see if we can move this block before it.
++ for (MachineBasicBlock *SuccBB : MBB->successors()) {
++#if 0
+ for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
+ E = MBB->succ_end(); SI != E; ++SI) {
++#endif
+ // Analyze the branch at the end of the block before the succ.
+- MachineBasicBlock *SuccBB = *SI;
+- MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
++ MachineFunction::iterator SuccPrev = --SuccBB->getIterator();
+
+ // If this block doesn't already fall-through to that successor, and if
+ // the succ doesn't already have a block that can fall through into it,
+@@ -1502,8 +1503,8 @@
+ SmallVector<MachineOperand, 4> PrevCond;
+ if (FallThrough != MF.end() &&
+ !TII->AnalyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) &&
+- PrevBB.isSuccessor(FallThrough)) {
+- MBB->moveAfter(--MF.end());
++ PrevBB.isSuccessor(&*FallThrough)) {
++ MBB->moveAfter(&MF.back());
+ MadeChange = true;
+ return MadeChange;
+ }
+@@ -1522,7 +1523,7 @@
+ bool BranchFolder::HoistCommonCode(MachineFunction &MF) {
+ bool MadeChange = false;
+ for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ) {
+- MachineBasicBlock *MBB = I++;
++ MachineBasicBlock *MBB = &*I++;
+ MadeChange |= HoistCommonCodeInSuccs(MBB);
+ }
+
+--- lib/CodeGen/CodeGenPrepare.cpp 2015-01-12 09:22:43.000000000 -0800
++++ lib/CodeGen/CodeGenPrepare.cpp 2015-12-06 14:55:51.313203408 -0800
+@@ -245,7 +245,8 @@
+ while (MadeChange) {
+ MadeChange = false;
+ for (Function::iterator I = F.begin(); I != F.end(); ) {
+- BasicBlock *BB = I++;
++ BasicBlock *BB = &*I;
++ ++I;
+ bool ModifiedDTOnIteration = false;
+ MadeChange |= OptimizeBlock(*BB, ModifiedDTOnIteration);
+
+@@ -311,7 +312,8 @@
+ bool Changed = false;
+ // Scan all of the blocks in the function, except for the entry block.
+ for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
+- BasicBlock *BB = I++;
++ BasicBlock *BB = &*I;
++ ++I;
+ // If the destination block has a single pred, then this is a trivial
+ // edge, just collapse it.
+ BasicBlock *SinglePred = BB->getSinglePredecessor();
+@@ -332,7 +334,7 @@
+ BB->moveBefore(&BB->getParent()->getEntryBlock());
+
+ // We have erased a block. Update the iterator.
+- I = BB;
++ I = BB->getIterator();
+ }
+ }
+ return Changed;
+@@ -347,7 +349,8 @@
+ bool MadeChange = false;
+ // Note that this intentionally skips the entry block.
+ for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
+- BasicBlock *BB = I++;
++ BasicBlock *BB = &*I;
++ ++I;
+
+ // If this block doesn't end with an uncond branch, ignore it.
+ BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
+@@ -356,7 +359,7 @@
+
+ // If the instruction before the branch (skipping debug info) isn't a phi
+ // node, then other stuff is happening here.
+- BasicBlock::iterator BBI = BI;
++ BasicBlock::iterator BBI(BI);
+ if (BBI != BB->begin()) {
+ --BBI;
+ while (isa<DbgInfoIntrinsic>(BBI)) {
+@@ -553,8 +556,8 @@
+ if (!InsertedCast) {
+ BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
+ InsertedCast =
+- CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
+- InsertPt);
++ CastInst::Create(CI->getOpcode(), CI->getOperand(0),
++ CI->getType(), "", &*InsertPt);
+ MadeChange = true;
+ }
+
+@@ -648,7 +651,7 @@
+ InsertedCmp =
+ CmpInst::Create(CI->getOpcode(),
+ CI->getPredicate(), CI->getOperand(0),
+- CI->getOperand(1), "", InsertPt);
++ CI->getOperand(1), "", &*InsertPt);
+ MadeChange = true;
+ }
+
+@@ -734,17 +737,17 @@
+ // Sink the shift
+ if (ShiftI->getOpcode() == Instruction::AShr)
+ InsertedShift =
+- BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
++ BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", &*InsertPt);
+ else
+ InsertedShift =
+- BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
++ BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", &*InsertPt);
+
+ // Sink the trunc
+ BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
+ TruncInsertPt++;
+
+ InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
+- TruncI->getType(), "", TruncInsertPt);
++ TruncI->getType(), "", &*TruncInsertPt);
+
+ MadeChange = true;
+
+@@ -829,10 +832,10 @@
+
+ if (ShiftI->getOpcode() == Instruction::AShr)
+ InsertedShift =
+- BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
++ BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", &*InsertPt);
+ else
+ InsertedShift =
+- BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
++ BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", &*InsertPt);
+
+ MadeChange = true;
+ }
+@@ -941,7 +944,7 @@
+ // %Elt = load i32* %EltAddr
+ // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
+ //
+- CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
++ CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
+ Builder.SetInsertPoint(InsertPt);
+
+ Value* Gep = Builder.CreateInBoundsGEP(FirstEltPtr, Builder.getInt32(Idx));
+@@ -949,7 +952,8 @@
+ VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
+
+ // Create "else" block, fill it in the next iteration
+- BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
++ BasicBlock *NewIfBlock =
++ CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
+ Builder.SetInsertPoint(InsertPt);
+ Instruction *OldBr = IfBlock->getTerminator();
+ BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
+@@ -1024,7 +1028,8 @@
+ // %to_store = icmp eq i1 %mask_1, true
+ // br i1 %to_load, label %cond.store, label %else
+ //
+- Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
++ Value *Predicate =
++ Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
+ Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
+ ConstantInt::get(Predicate->getType(), 1));
+
+@@ -1034,15 +1039,17 @@
+ // %EltAddr = getelementptr i32* %1, i32 0
+ // %store i32 %OneElt, i32* %EltAddr
+ //
+- BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
++ BasicBlock *CondBlock =
++ IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
+ Builder.SetInsertPoint(InsertPt);
+-
++
+ Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
+ Value* Gep = Builder.CreateInBoundsGEP(FirstEltPtr, Builder.getInt32(Idx));
+ Builder.CreateStore(OneElt, Gep);
+
+ // Create "else" block, fill it in the next iteration
+- BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
++ BasicBlock *NewIfBlock =
++ CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
+ Builder.SetInsertPoint(InsertPt);
+ Instruction *OldBr = IfBlock->getTerminator();
+ BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
+@@ -1085,7 +1092,7 @@
+ // Substituting this can cause recursive simplifications, which can
+ // invalidate our iterator. Use a WeakVH to hold onto it in case this
+ // happens.
+- WeakVH IterHandle(CurInstIterator);
++ WeakVH IterHandle(&*CurInstIterator);
+
+ replaceAndRecursivelySimplify(CI, RetVal,
+ TLI ? TLI->getDataLayout() : nullptr,
+@@ -1093,7 +1100,7 @@
+
+ // If the iterator instruction was recursively deleted, start over at the
+ // start of the block.
+- if (IterHandle != CurInstIterator) {
++ if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
+ CurInstIterator = BB->begin();
+ SunkAddrs.clear();
+ }
+@@ -1410,10 +1417,10 @@
+ public:
+ /// \brief Record the position of \p Inst.
+ InsertionHandler(Instruction *Inst) {
+- BasicBlock::iterator It = Inst;
++ BasicBlock::iterator It = Inst->getIterator();
+ HasPrevInstruction = (It != (Inst->getParent()->begin()));
+ if (HasPrevInstruction)
+- Point.PrevInst = --It;
++ Point.PrevInst = &*--It;
+ else
+ Point.BB = Inst->getParent();
+ }
+@@ -1425,7 +1432,7 @@
+ Inst->removeFromParent();
+ Inst->insertAfter(Point.PrevInst);
+ } else {
+- Instruction *Position = Point.BB->getFirstInsertionPt();
++ Instruction *Position = &*Point.BB->getFirstInsertionPt();
+ if (Inst->getParent())
+ Inst->moveBefore(Position);
+ else
+@@ -3191,12 +3198,12 @@
+ if (Repl->use_empty()) {
+ // This can cause recursive deletion, which can invalidate our iterator.
+ // Use a WeakVH to hold onto it in case this happens.
+- WeakVH IterHandle(CurInstIterator);
++ WeakVH IterHandle(&*CurInstIterator);
+ BasicBlock *BB = CurInstIterator->getParent();
+
+ RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
+
+- if (IterHandle != CurInstIterator) {
++ if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
+ // If the iterator instruction was recursively deleted, start over at the
+ // start of the block.
+ CurInstIterator = BB->begin();
+@@ -3495,7 +3502,7 @@
+
+ if (!InsertedTrunc) {
+ BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
+- InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
++ InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
+ InsertedTruncsSet.insert(InsertedTrunc);
+ }
+
+@@ -3583,7 +3590,8 @@
+ BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
+
+ // The select itself is replaced with a PHI Node.
+- PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
++ PHINode *PN = PHINode::Create(SI->getType(), 2, "",
++ &NextBlock->front());
+ PN->takeName(SI);
+ PN->addIncoming(SI->getTrueValue(), StartBlock);
+ PN->addIncoming(SI->getFalseValue(), SmallBlock);
+@@ -3646,7 +3654,8 @@
+ BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
+ InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
+ SVI->getOperand(1),
+- SVI->getOperand(2), "", InsertPt);
++ SVI->getOperand(2), "",
++ &*InsertPt);
+ }
+
+ UI->replaceUsesOfWith(SVI, InsertedShuffle);
+@@ -3969,148 +3978,6 @@
+ Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
+ }
+
+-// See if we can speculate calls to intrinsic cttz/ctlz.
+-//
+-// Example:
+-// entry:
+-// ...
+-// %cmp = icmp eq i64 %val, 0
+-// br i1 %cmp, label %end.bb, label %then.bb
+-//
+-// then.bb:
+-// %c = tail call i64 @llvm.cttz.i64(i64 %val, i1 true)
+-// br label %EndBB
+-//
+-// end.bb:
+-// %cond = phi i64 [ %c, %then.bb ], [ 64, %entry ]
+-//
+-// ==>
+-//
+-// entry:
+-// ...
+-// %c = tail call i64 @llvm.cttz.i64(i64 %val, i1 false)
+-//
+-static bool OptimizeBranchInst(BranchInst *BrInst, const TargetLowering &TLI) {
+- assert(BrInst->isConditional() && "Expected a conditional branch!");
+- BasicBlock *ThenBB = BrInst->getSuccessor(1);
+- BasicBlock *EndBB = BrInst->getSuccessor(0);
+-
+- // See if ThenBB contains only one instruction (excluding the
+- // terminator and DbgInfoIntrinsic calls).
+- IntrinsicInst *II = nullptr;
+- CastInst *CI = nullptr;
+- for (BasicBlock::iterator I = ThenBB->begin(),
+- E = std::prev(ThenBB->end()); I != E; ++I) {
+- // Skip debug info.
+- if (isa<DbgInfoIntrinsic>(I))
+- continue;
+-
+- // Check if this is a zero extension or a truncate of a previously
+- // matched call to intrinsic cttz/ctlz.
+- if (II) {
+- // Early exit if we already found a "free" zero extend/truncate.
+- if (CI)
+- return false;
+-
+- Type *SrcTy = II->getType();
+- Type *DestTy = I->getType();
+- Value *V;
+-
+- if (match(cast<Instruction>(I), m_ZExt(m_Value(V))) && V == II) {
+- // Speculate this zero extend only if it is "free" for the target.
+- if (TLI.isZExtFree(SrcTy, DestTy)) {
+- CI = cast<CastInst>(I);
+- continue;
+- }
+- } else if (match(cast<Instruction>(I), m_Trunc(m_Value(V))) && V == II) {
+- // Speculate this truncate only if it is "free" for the target.
+- if (TLI.isTruncateFree(SrcTy, DestTy)) {
+- CI = cast<CastInst>(I);
+- continue;
+- }
+- } else {
+- // Avoid speculating more than one instruction.
+- return false;
+- }
+- }
+-
+- // See if this is a call to intrinsic cttz/ctlz.
+- if (match(cast<Instruction>(I), m_Intrinsic<Intrinsic::cttz>())) {
+- // Avoid speculating expensive intrinsic calls.
+- if (!TLI.isCheapToSpeculateCttz())
+- return false;
+- }
+- else if (match(cast<Instruction>(I), m_Intrinsic<Intrinsic::ctlz>())) {
+- // Avoid speculating expensive intrinsic calls.
+- if (!TLI.isCheapToSpeculateCtlz())
+- return false;
+- } else
+- return false;
+-
+- II = cast<IntrinsicInst>(I);
+- }
+-
+- // Look for PHI nodes with 'II' as the incoming value from 'ThenBB'.
+- BasicBlock *EntryBB = BrInst->getParent();
+- for (BasicBlock::iterator I = EndBB->begin();
+- PHINode *PN = dyn_cast<PHINode>(I); ++I) {
+- Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
+- Value *OrigV = PN->getIncomingValueForBlock(EntryBB);
+-
+- if (!OrigV)
+- return false;
+-
+- if (ThenV != II && (!CI || ThenV != CI))
+- return false;
+-
+- if (ConstantInt *CInt = dyn_cast<ConstantInt>(OrigV)) {
+- unsigned BitWidth = II->getType()->getIntegerBitWidth();
+-
+- // Don't try to simplify this phi node if 'ThenV' is a cttz/ctlz
+- // intrinsic call, but 'OrigV' is not equal to the 'size-of' in bits
+- // of the value in input to the cttz/ctlz.
+- if (CInt->getValue() != BitWidth)
+- return false;
+-
+- // Hoist the call to cttz/ctlz from ThenBB into EntryBB.
+- EntryBB->getInstList().splice(BrInst, ThenBB->getInstList(),
+- ThenBB->begin(), std::prev(ThenBB->end()));
+-
+- // Update PN setting ThenV as the incoming value from both 'EntryBB'
+- // and 'ThenBB'. Eventually, method 'OptimizeInst' will fold this
+- // phi node if all the incoming values are the same.
+- PN->setIncomingValue(PN->getBasicBlockIndex(EntryBB), ThenV);
+- PN->setIncomingValue(PN->getBasicBlockIndex(ThenBB), ThenV);
+-
+- // Clear the 'undef on zero' flag of the cttz/ctlz intrinsic call.
+- if (cast<ConstantInt>(II->getArgOperand(1))->isOne()) {
+- Type *Ty = II->getArgOperand(0)->getType();
+- Value *Args[] = { II->getArgOperand(0),
+- ConstantInt::getFalse(II->getContext()) };
+- Module *M = EntryBB->getParent()->getParent();
+- Value *IF = Intrinsic::getDeclaration(M, II->getIntrinsicID(), Ty);
+- IRBuilder<> Builder(II);
+- Instruction *NewI = Builder.CreateCall(IF, Args);
+-
+- // Replace the old call to cttz/ctlz.
+- II->replaceAllUsesWith(NewI);
+- II->eraseFromParent();
+- }
+-
+- // Update BrInst condition so that the branch to EndBB is always taken.
+- // Later on, method 'ConstantFoldTerminator' will simplify this branch
+- // replacing it with a direct branch to 'EndBB'.
+- // As a side effect, CodeGenPrepare will attempt to simplify the control
+- // flow graph by deleting basic block 'ThenBB' and merging 'EntryBB' into
+- // 'EndBB' (calling method 'EliminateFallThrough').
+- BrInst->setCondition(ConstantInt::getTrue(BrInst->getContext()));
+- return true;
+- }
+- }
+-
+- return false;
+-}
+-
+ /// Some targets can do store(extractelement) with one instruction.
+ /// Try to push the extractelement towards the stores when the target
+ /// has this feature and this is profitable.
+@@ -4263,34 +4130,6 @@
+ if (isa<ExtractElementInst>(I))
+ return OptimizeExtractElementInst(I);
+
+- if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
+- if (TLI && BI->isConditional() && BI->getCondition()->hasOneUse()) {
+- // Check if the branch condition compares a value agaist zero.
+- if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
+- if (ICI->getPredicate() == ICmpInst::ICMP_EQ &&
+- match(ICI->getOperand(1), m_Zero())) {
+- BasicBlock *ThenBB = BI->getSuccessor(1);
+- BasicBlock *EndBB = BI->getSuccessor(0);
+-
+- // Check if ThenBB is only reachable from this basic block; also,
+- // check if EndBB has more than one predecessor.
+- if (ThenBB->getSinglePredecessor() &&
+- !EndBB->getSinglePredecessor()) {
+- TerminatorInst *TI = ThenBB->getTerminator();
+-
+- if (TI->getNumSuccessors() == 1 && TI->getSuccessor(0) == EndBB &&
+- // Try to speculate calls to intrinsic cttz/ctlz from 'ThenBB'.
+- OptimizeBranchInst(BI, *TLI)) {
+- ModifiedDT = true;
+- return true;
+- }
+- }
+- }
+- }
+- }
+- return false;
+- }
+-
+ return false;
+ }
+
+@@ -4303,7 +4142,7 @@
+
+ CurInstIterator = BB.begin();
+ while (CurInstIterator != BB.end()) {
+- MadeChange |= OptimizeInst(CurInstIterator++, ModifiedDT);
++ MadeChange |= OptimizeInst(&*CurInstIterator++, ModifiedDT);
+ if (ModifiedDT)
+ return true;
+ }
+@@ -4320,7 +4159,7 @@
+ for (BasicBlock &BB : F) {
+ Instruction *PrevNonDbgInst = nullptr;
+ for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
+- Instruction *Insn = BI++;
++ Instruction *Insn = &*BI++;
+ DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
+ // Leave dbg.values that refer to an alloca alone. These
+ // instrinsics describe the address of a variable (= the alloca)
+@@ -4337,7 +4176,7 @@
+ DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
+ DVI->removeFromParent();
+ if (isa<PHINode>(VI))
+- DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
++ DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
+ else
+ DVI->insertAfter(VI);
+ MadeChange = true;
+@@ -4361,7 +4200,7 @@
+ return false;
+ bool MadeChange = false;
+ for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
+- BasicBlock *BB = I++;
++ BasicBlock *BB = &*I++;
+
+ // Does this BB end with the following?
+ // %andVal = and %val, #single-bit-set
+--- lib/CodeGen/DFAPacketizer.cpp 2014-10-13 18:03:16.000000000 -0700
++++ lib/CodeGen/DFAPacketizer.cpp 2015-12-06 18:00:08.967241318 -0800
+@@ -147,7 +147,7 @@
+ MachineInstr *MI) {
+ if (CurrentPacketMIs.size() > 1) {
+ MachineInstr *MIFirst = CurrentPacketMIs.front();
+- finalizeBundle(*MBB, MIFirst, MI);
++ finalizeBundle(*MBB, MIFirst->getIterator(), MI->getIterator());
+ }
+ CurrentPacketMIs.clear();
+ ResourceTracker->clearResources();
+--- lib/CodeGen/ExecutionDepsFix.cpp 2014-12-17 11:13:47.000000000 -0800
++++ lib/CodeGen/ExecutionDepsFix.cpp 2015-12-06 14:03:54.050682968 -0800
+@@ -753,7 +753,7 @@
+ AliasMap[*AI].push_back(i);
+ }
+
+- MachineBasicBlock *Entry = MF->begin();
++ MachineBasicBlock *Entry = &*MF->begin();
+ ReversePostOrderTraversal<MachineBasicBlock*> RPOT(Entry);
+ SmallVector<MachineBasicBlock*, 16> Loops;
+ for (ReversePostOrderTraversal<MachineBasicBlock*>::rpo_iterator
+--- lib/CodeGen/ExpandISelPseudos.cpp 2014-10-14 00:22:08.000000000 -0700
++++ lib/CodeGen/ExpandISelPseudos.cpp 2015-12-06 14:17:23.351013837 -0800
+@@ -50,7 +50,7 @@
+
+ // Iterate through each instruction in the function, looking for pseudos.
+ for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
+- MachineBasicBlock *MBB = I;
++ MachineBasicBlock *MBB = &*I;
+ for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
+ MBBI != MBBE; ) {
+ MachineInstr *MI = MBBI++;
+@@ -63,7 +63,7 @@
+ // The expansion may involve new basic blocks.
+ if (NewMBB != MBB) {
+ MBB = NewMBB;
+- I = NewMBB;
++ I = NewMBB->getIterator();
+ MBBI = NewMBB->begin();
+ MBBE = NewMBB->end();
+ }
+--- lib/CodeGen/ForwardControlFlowIntegrity.cpp 2015-01-14 03:23:27.000000000 -0800
++++ lib/CodeGen/ForwardControlFlowIntegrity.cpp 2015-12-06 18:01:31.650156258 -0800
+@@ -329,7 +329,7 @@
+ Check = TempBuilder.CreateICmpEQ(NewFunPtr, FunPtr);
+ BasicBlock *InvalidPtrBlock =
+ BasicBlock::Create(M.getContext(), "invalid.ptr", CurF, 0);
+- BasicBlock *ContinuationBB = CurBB->splitBasicBlock(I);
++ BasicBlock *ContinuationBB = CurBB->splitBasicBlock(I->getIterator());
+
+ // Remove the unconditional branch that connects the two blocks.
+ TerminatorInst *TermInst = CurBB->getTerminator();
+--- lib/CodeGen/GCStrategy.cpp 2015-01-07 11:07:50.000000000 -0800
++++ lib/CodeGen/GCStrategy.cpp 2015-12-06 18:08:32.675654207 -0800
+@@ -156,12 +156,13 @@
+ unsigned Count) {
+ // Scroll past alloca instructions.
+ BasicBlock::iterator IP = F.getEntryBlock().begin();
+- while (isa<AllocaInst>(IP)) ++IP;
++ while (isa<AllocaInst>(IP))
++ ++IP;
+
+ // Search for initializers in the initial BB.
+ SmallPtrSet<AllocaInst*,16> InitedRoots;
+- for (; !CouldBecomeSafePoint(IP); ++IP)
+- if (StoreInst *SI = dyn_cast<StoreInst>(IP))
++ for (; !CouldBecomeSafePoint(&*IP); ++IP)
++ if (StoreInst *SI = dyn_cast<StoreInst>(&*IP))
+ if (AllocaInst *AI =
+ dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
+ InitedRoots.insert(AI);
+--- lib/CodeGen/GlobalMerge.cpp 2015-01-14 03:23:27.000000000 -0800
++++ lib/CodeGen/GlobalMerge.cpp 2015-12-06 18:44:54.895620825 -0800
+@@ -289,61 +289,61 @@
+ setMustKeepGlobalVariables(M);
+
+ // Grab all non-const globals.
+- for (Module::global_iterator I = M.global_begin(),
+- E = M.global_end(); I != E; ++I) {
++ for (auto &I : M.globals()) {
+ // Merge is safe for "normal" internal or external globals only
+- if (I->isDeclaration() || I->isThreadLocal() || I->hasSection())
++ if (I.isDeclaration() || I.isThreadLocal() || I.hasSection())
+ continue;
+
+- if (!(EnableGlobalMergeOnExternal && I->hasExternalLinkage()) &&
+- !I->hasInternalLinkage())
++ if (!(EnableGlobalMergeOnExternal && I.hasExternalLinkage()) &&
++ !I.hasInternalLinkage())
+ continue;
+
+- PointerType *PT = dyn_cast<PointerType>(I->getType());
++ PointerType *PT = dyn_cast<PointerType>(I.getType());
+ assert(PT && "Global variable is not a pointer!");
+
+ unsigned AddressSpace = PT->getAddressSpace();
+
+ // Ignore fancy-aligned globals for now.
+- unsigned Alignment = DL->getPreferredAlignment(I);
+- Type *Ty = I->getType()->getElementType();
++ unsigned Alignment = DL->getPreferredAlignment(&I);
++ Type *Ty = I.getType()->getElementType();
+ if (Alignment > DL->getABITypeAlignment(Ty))
+ continue;
+
+ // Ignore all 'special' globals.
+- if (I->getName().startswith("llvm.") ||
+- I->getName().startswith(".llvm."))
++ if (I.getName().startswith("llvm.") ||
++ I.getName().startswith(".llvm."))
+ continue;
+
+ // Ignore all "required" globals:
+- if (isMustKeepGlobalVariable(I))
++ if (isMustKeepGlobalVariable(&I))
+ continue;
+
+ if (DL->getTypeAllocSize(Ty) < MaxOffset) {
+- if (TargetLoweringObjectFile::getKindForGlobal(I, *TM).isBSSLocal())
+- BSSGlobals[AddressSpace].push_back(I);
+- else if (I->isConstant())
+- ConstGlobals[AddressSpace].push_back(I);
++ if (TargetLoweringObjectFile::getKindForGlobal(&I, *TM).isBSSLocal())
++ BSSGlobals[AddressSpace].push_back(&I);
++ else if (I.isConstant())
++ ConstGlobals[AddressSpace].push_back(&I);
+ else
+- Globals[AddressSpace].push_back(I);
++ Globals[AddressSpace].push_back(&I);
+ }
+ }
+
+- for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
+- I = Globals.begin(), E = Globals.end(); I != E; ++I)
+- if (I->second.size() > 1)
+- Changed |= doMerge(I->second, M, false, I->first);
+-
+- for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
+- I = BSSGlobals.begin(), E = BSSGlobals.end(); I != E; ++I)
+- if (I->second.size() > 1)
+- Changed |= doMerge(I->second, M, false, I->first);
+-
+- if (EnableGlobalMergeOnConst)
+- for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
+- I = ConstGlobals.begin(), E = ConstGlobals.end(); I != E; ++I)
+- if (I->second.size() > 1)
+- Changed |= doMerge(I->second, M, true, I->first);
++ for (auto &G : Globals) {
++ if (G.second.size() > 1)
++ Changed |= doMerge(G.second, M, false, G.first);
++ }
++
++ for (auto &G : BSSGlobals) {
++ if (G.second.size() > 1)
++ Changed |= doMerge(G.second, M, false, G.first);
++ }
++
++ if (EnableGlobalMergeOnConst) {
++ for (auto &G : ConstGlobals) {
++ if (G.second.size() > 1)
++ Changed |= doMerge(G.second, M, true, G.first);
++ }
++ }
+
+ return Changed;
+ }
+--- lib/CodeGen/IfConversion.cpp 2014-10-14 00:22:08.000000000 -0700
++++ lib/CodeGen/IfConversion.cpp 2015-12-06 19:35:07.755981678 -0800
+@@ -460,11 +460,15 @@
+ /// getNextBlock - Returns the next block in the function blocks ordering. If
+ /// it is the end, returns NULL.
+ static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
+- MachineFunction::iterator I = BB;
++ MachineFunction::iterator I = BB->getIterator();
+ MachineFunction::iterator E = BB->getParent()->end();
++ if (I == E)
++ return nullptr;
++
+ if (++I == E)
+ return nullptr;
+- return I;
++
++ return &*I;
+ }
+
+ /// ValidSimple - Returns true if the 'true' block (along with its
+@@ -528,12 +532,13 @@
+
+ MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
+ if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
+- MachineFunction::iterator I = TrueBBI.BB;
++ MachineFunction::iterator I = TrueBBI.BB->getIterator();
+ if (++I == TrueBBI.BB->getParent()->end())
+ return false;
+- TExit = I;
++
++ TExit = &*I;
+ }
+- return TExit && TExit == FalseBBI.BB;
++ return TExit && (TExit == FalseBBI.BB);
+ }
+
+ /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
+@@ -910,10 +915,8 @@
+ /// candidates.
+ void IfConverter::AnalyzeBlocks(MachineFunction &MF,
+ std::vector<IfcvtToken*> &Tokens) {
+- for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
+- MachineBasicBlock *BB = I;
+- AnalyzeBlock(BB, Tokens);
+- }
++ for (auto &BB : MF)
++ AnalyzeBlock(&BB, Tokens);
+
+ // Sort to favor more complex ifcvt scheme.
+ std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
+@@ -923,14 +926,14 @@
+ /// that all the intervening blocks are empty (given BB can fall through to its
+ /// next block).
+ static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
+- MachineFunction::iterator PI = BB;
++ MachineFunction::iterator PI = BB->getIterator();
+ MachineFunction::iterator I = std::next(PI);
+- MachineFunction::iterator TI = ToBB;
++ MachineFunction::iterator TI = ToBB->getIterator();
+ MachineFunction::iterator E = BB->getParent()->end();
+ while (I != TI) {
+ // Check isSuccessor to avoid case where the next block is empty, but
+ // it's not a successor.
+- if (I == E || !I->empty() || !PI->isSuccessor(I))
++ if (I == E || !I->empty() || !PI->isSuccessor(&*I))
+ return false;
+ PI = I++;
+ }
+--- lib/CodeGen/InterferenceCache.cpp 2014-04-21 19:02:50.000000000 -0700
++++ lib/CodeGen/InterferenceCache.cpp 2015-12-06 19:36:56.386076813 -0800
+@@ -143,7 +143,8 @@
+ PrevPos = Start;
+ }
+
+- MachineFunction::const_iterator MFI = MF->getBlockNumbered(MBBNum);
++ MachineFunction::const_iterator MFI =
++ MF->getBlockNumbered(MBBNum)->getIterator();
+ BlockInterference *BI = &Blocks[MBBNum];
+ ArrayRef<SlotIndex> RegMaskSlots;
+ ArrayRef<const uint32_t*> RegMaskBits;
+--- lib/CodeGen/IntrinsicLowering.cpp 2014-08-30 11:33:35.000000000 -0700
++++ lib/CodeGen/IntrinsicLowering.cpp 2015-12-06 19:45:17.855570385 -0800
+@@ -75,7 +75,7 @@
+ Constant* FCache = M->getOrInsertFunction(NewFn,
+ FunctionType::get(RetTy, ParamTys, false));
+
+- IRBuilder<> Builder(CI->getParent(), CI);
++ IRBuilder<> Builder(CI->getParent(), CI->getIterator());
+ SmallVector<Value *, 8> Args(ArgBegin, ArgEnd);
+ CallInst *NewCI = Builder.CreateCall(FCache, Args);
+ NewCI->setName(CI->getName());
+@@ -94,71 +94,73 @@
+
+ void IntrinsicLowering::AddPrototypes(Module &M) {
+ LLVMContext &Context = M.getContext();
+- for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
+- if (I->isDeclaration() && !I->use_empty())
+- switch (I->getIntrinsicID()) {
++ for (auto &I : M) {
++ if (I.isDeclaration() && !I.use_empty()) {
++ switch (I.getIntrinsicID()) {
+ default: break;
+ case Intrinsic::setjmp:
+- EnsureFunctionExists(M, "setjmp", I->arg_begin(), I->arg_end(),
+- Type::getInt32Ty(M.getContext()));
+- break;
++ EnsureFunctionExists(M, "setjmp", I.arg_begin(), I.arg_end(),
++ Type::getInt32Ty(M.getContext()));
++ break;
+ case Intrinsic::longjmp:
+- EnsureFunctionExists(M, "longjmp", I->arg_begin(), I->arg_end(),
+- Type::getVoidTy(M.getContext()));
+- break;
++ EnsureFunctionExists(M, "longjmp", I.arg_begin(), I.arg_end(),
++ Type::getVoidTy(M.getContext()));
++ break;
+ case Intrinsic::siglongjmp:
+- EnsureFunctionExists(M, "abort", I->arg_end(), I->arg_end(),
+- Type::getVoidTy(M.getContext()));
+- break;
++ EnsureFunctionExists(M, "abort", I.arg_end(), I.arg_end(),
++ Type::getVoidTy(M.getContext()));
++ break;
+ case Intrinsic::memcpy:
+- M.getOrInsertFunction("memcpy",
+- Type::getInt8PtrTy(Context),
+- Type::getInt8PtrTy(Context),
+- Type::getInt8PtrTy(Context),
+- DL.getIntPtrType(Context), nullptr);
+- break;
++ M.getOrInsertFunction("memcpy",
++ Type::getInt8PtrTy(Context),
++ Type::getInt8PtrTy(Context),
++ Type::getInt8PtrTy(Context),
++ DL.getIntPtrType(Context), nullptr);
++ break;
+ case Intrinsic::memmove:
+- M.getOrInsertFunction("memmove",
+- Type::getInt8PtrTy(Context),
+- Type::getInt8PtrTy(Context),
+- Type::getInt8PtrTy(Context),
+- DL.getIntPtrType(Context), nullptr);
+- break;
++ M.getOrInsertFunction("memmove",
++ Type::getInt8PtrTy(Context),
++ Type::getInt8PtrTy(Context),
++ Type::getInt8PtrTy(Context),
++ DL.getIntPtrType(Context), nullptr);
++ break;
+ case Intrinsic::memset:
+- M.getOrInsertFunction("memset",
+- Type::getInt8PtrTy(Context),
+- Type::getInt8PtrTy(Context),
+- Type::getInt32Ty(M.getContext()),
+- DL.getIntPtrType(Context), nullptr);
+- break;
++ M.getOrInsertFunction("memset",
++ Type::getInt8PtrTy(Context),
++ Type::getInt8PtrTy(Context),
++ Type::getInt32Ty(M.getContext()),
++ DL.getIntPtrType(Context), nullptr);
++ break;
+ case Intrinsic::sqrt:
+- EnsureFPIntrinsicsExist(M, I, "sqrtf", "sqrt", "sqrtl");
+- break;
++ EnsureFPIntrinsicsExist(M, &I, "sqrtf", "sqrt", "sqrtl");
++ break;
+ case Intrinsic::sin:
+- EnsureFPIntrinsicsExist(M, I, "sinf", "sin", "sinl");
+- break;
++ EnsureFPIntrinsicsExist(M, &I, "sinf", "sin", "sinl");
++ break;
+ case Intrinsic::cos:
+- EnsureFPIntrinsicsExist(M, I, "cosf", "cos", "cosl");
+- break;
++ EnsureFPIntrinsicsExist(M, &I, "cosf", "cos", "cosl");
++ break;
+ case Intrinsic::pow:
+- EnsureFPIntrinsicsExist(M, I, "powf", "pow", "powl");
+- break;
++ EnsureFPIntrinsicsExist(M, &I, "powf", "pow", "powl");
++ break;
+ case Intrinsic::log:
+- EnsureFPIntrinsicsExist(M, I, "logf", "log", "logl");
+- break;
++ EnsureFPIntrinsicsExist(M, &I, "logf", "log", "logl");
++ break;
+ case Intrinsic::log2:
+- EnsureFPIntrinsicsExist(M, I, "log2f", "log2", "log2l");
+- break;
++ EnsureFPIntrinsicsExist(M, &I, "log2f", "log2", "log2l");
++ break;
+ case Intrinsic::log10:
+- EnsureFPIntrinsicsExist(M, I, "log10f", "log10", "log10l");
+- break;
++ EnsureFPIntrinsicsExist(M, &I, "log10f", "log10", "log10l");
++ break;
+ case Intrinsic::exp:
+- EnsureFPIntrinsicsExist(M, I, "expf", "exp", "expl");
+- break;
++ EnsureFPIntrinsicsExist(M, &I, "expf", "exp", "expl");
++ break;
+ case Intrinsic::exp2:
+- EnsureFPIntrinsicsExist(M, I, "exp2f", "exp2", "exp2l");
+- break;
++ EnsureFPIntrinsicsExist(M, &I, "exp2f", "exp2", "exp2l");
++ break;
+ }
++ }
++ }
+ }
+
+ /// LowerBSWAP - Emit the code to lower bswap of V before the specified
+@@ -168,7 +170,7 @@
+
+ unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
+
+- IRBuilder<> Builder(IP->getParent(), IP);
++ IRBuilder<> Builder(IP->getParent(), IP->getIterator());
+
+ switch(BitSize) {
+ default: llvm_unreachable("Unhandled type size of value to byteswap!");
+@@ -268,7 +270,7 @@
+ 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
+ };
+
+- IRBuilder<> Builder(IP->getParent(), IP);
++ IRBuilder<> Builder(IP->getParent(), IP->getIterator());
+
+ unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
+ unsigned WordSize = (BitSize + 63) / 64;
+@@ -301,7 +303,7 @@
+ /// instruction IP.
+ static Value *LowerCTLZ(LLVMContext &Context, Value *V, Instruction *IP) {
+
+- IRBuilder<> Builder(IP->getParent(), IP);
++ IRBuilder<> Builder(IP->getParent(), IP->getIterator());
+
+ unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
+ for (unsigned i = 1; i < BitSize; i <<= 1) {
+@@ -338,7 +340,7 @@
+ }
+
+ void IntrinsicLowering::LowerIntrinsicCall(CallInst *CI) {
+- IRBuilder<> Builder(CI->getParent(), CI);
++ IRBuilder<> Builder(CI->getParent(), CI->getIterator());
+ LLVMContext &Context = CI->getContext();
+
+ const Function *Callee = CI->getCalledFunction();
+--- lib/CodeGen/LiveDebugVariables.cpp 2015-01-14 03:23:27.000000000 -0800
++++ lib/CodeGen/LiveDebugVariables.cpp 2015-12-06 19:51:37.891248865 -0800
+@@ -480,7 +480,7 @@
+ bool Changed = false;
+ for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
+ ++MFI) {
+- MachineBasicBlock *MBB = MFI;
++ MachineBasicBlock *MBB = &*MFI;
+ for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
+ MBBI != MBBE;) {
+ if (!MBBI->isDebugValue()) {
+@@ -974,11 +974,11 @@
+ SlotIndex Stop = I.stop();
+ unsigned LocNo = I.value();
+ DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo);
+- MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start);
+- SlotIndex MBBEnd = LIS.getMBBEndIdx(MBB);
++ MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
++ SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
+
+ DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
+- insertDebugValue(MBB, Start, LocNo, LIS, TII);
++ insertDebugValue(&*MBB, Start, LocNo, LIS, TII);
+ // This interval may span multiple basic blocks.
+ // Insert a DBG_VALUE into each one.
+ while(Stop > MBBEnd) {
+@@ -986,9 +986,9 @@
+ Start = MBBEnd;
+ if (++MBB == MFEnd)
+ break;
+- MBBEnd = LIS.getMBBEndIdx(MBB);
++ MBBEnd = LIS.getMBBEndIdx(&*MBB);
+ DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
+- insertDebugValue(MBB, Start, LocNo, LIS, TII);
++ insertDebugValue(&*MBB, Start, LocNo, LIS, TII);
+ }
+ DEBUG(dbgs() << '\n');
+ if (MBB == MFEnd)
+--- lib/CodeGen/LiveIntervalAnalysis.cpp 2014-12-23 18:11:43.000000000 -0800
++++ lib/CodeGen/LiveIntervalAnalysis.cpp 2015-12-06 19:52:56.875852273 -0800
+@@ -211,7 +211,7 @@
+ // Find all instructions with regmask operands.
+ for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
+ MBBI != E; ++MBBI) {
+- MachineBasicBlock *MBB = MBBI;
++ MachineBasicBlock *MBB = &*MBBI;
+ std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB->getNumber()];
+ RMB.first = RegMaskSlots.size();
+ for (MachineBasicBlock::iterator MI = MBB->begin(), ME = MBB->end();
+@@ -285,7 +285,7 @@
+ // Check all basic blocks for live-ins.
+ for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
+ MFI != MFE; ++MFI) {
+- const MachineBasicBlock *MBB = MFI;
++ const MachineBasicBlock *MBB = &*MFI;
+
+ // We only care about ABI blocks: Entry + landing pads.
+ if ((MFI != MF->begin() && !MBB->isLandingPad()) || MBB->livein_empty())
+--- lib/CodeGen/LiveVariables.cpp 2014-10-14 00:22:08.000000000 -0700
++++ lib/CodeGen/LiveVariables.cpp 2015-12-06 19:54:20.348152143 -0800
+@@ -639,7 +639,7 @@
+ // function. This guarantees that we will see the definition of a virtual
+ // register before its uses due to dominance properties of SSA (except for PHI
+ // nodes, which are treated as a special case).
+- MachineBasicBlock *Entry = MF->begin();
++ MachineBasicBlock *Entry = &MF->front();
+ SmallPtrSet<MachineBasicBlock*,16> Visited;
+
+ for (MachineBasicBlock *MBB : depth_first_ext(Entry, Visited)) {
+--- lib/CodeGen/LocalStackSlotAllocation.cpp 2014-12-01 14:52:56.000000000 -0800
++++ lib/CodeGen/LocalStackSlotAllocation.cpp 2015-12-06 19:56:09.955965495 -0800
+@@ -324,7 +324,7 @@
+ // Sort the frame references by local offset
+ array_pod_sort(FrameReferenceInsns.begin(), FrameReferenceInsns.end());
+
+- MachineBasicBlock *Entry = Fn.begin();
++ MachineBasicBlock *Entry = &Fn.front();
+
+ unsigned BaseReg = 0;
+ int64_t BaseOffset = 0;
+--- lib/CodeGen/MachineBasicBlock.cpp 2014-12-22 05:00:36.000000000 -0800
++++ lib/CodeGen/MachineBasicBlock.cpp 2015-12-06 20:28:52.972371805 -0800
+@@ -300,8 +300,8 @@
+
+ for (const_instr_iterator I = instr_begin(); I != instr_end(); ++I) {
+ if (Indexes) {
+- if (Indexes->hasIndex(I))
+- OS << Indexes->getInstructionIndex(I);
++ if (Indexes->hasIndex(&*I))
++ OS << Indexes->getInstructionIndex(&*I);
+ OS << '\t';
+ }
+ OS << '\t';
+@@ -372,12 +372,11 @@
+ }
+
+ void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
+- getParent()->splice(NewAfter, this);
++ getParent()->splice(NewAfter->getIterator(), getIterator());
+ }
+
+ void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
+- MachineFunction::iterator BBI = NewBefore;
+- getParent()->splice(++BBI, this);
++ getParent()->splice(++NewBefore->getIterator(), getIterator());
+ }
+
+ void MachineBasicBlock::updateTerminator() {
+@@ -623,14 +622,14 @@
+ }
+
+ bool MachineBasicBlock::canFallThrough() {
+- MachineFunction::iterator Fallthrough = this;
++ MachineFunction::iterator Fallthrough = getIterator();
+ ++Fallthrough;
+ // If FallthroughBlock is off the end of the function, it can't fall through.
+ if (Fallthrough == getParent()->end())
+ return false;
+
+ // If FallthroughBlock isn't a successor, no fallthrough is possible.
+- if (!isSuccessor(Fallthrough))
++ if (!isSuccessor(&*Fallthrough))
+ return false;
+
+ // Analyze the branches, if any, at the end of the block.
+@@ -721,7 +720,7 @@
+ if (LV)
+ for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
+ I != E; ++I) {
+- MachineInstr *MI = I;
++ MachineInstr *MI = &*I;
+ for (MachineInstr::mop_iterator OI = MI->operands_begin(),
+ OE = MI->operands_end(); OI != OE; ++OI) {
+ if (!OI->isReg() || OI->getReg() == 0 ||
+@@ -741,7 +740,7 @@
+ if (LIS) {
+ for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
+ I != E; ++I) {
+- MachineInstr *MI = I;
++ MachineInstr *MI = &*I;
+
+ for (MachineInstr::mop_iterator OI = MI->operands_begin(),
+ OE = MI->operands_end(); OI != OE; ++OI) {
+@@ -763,7 +762,7 @@
+ if (Indexes) {
+ for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
+ I != E; ++I)
+- Terminators.push_back(I);
++ Terminators.push_back(&*I);
+ }
+
+ updateTerminator();
+@@ -772,7 +771,7 @@
+ SmallVector<MachineInstr*, 4> NewTerminators;
+ for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
+ I != E; ++I)
+- NewTerminators.push_back(I);
++ NewTerminators.push_back(&*I);
+
+ for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
+ E = Terminators.end(); I != E; ++I) {
+@@ -794,9 +793,9 @@
+ I != E; ++I) {
+ // Some instructions may have been moved to NMBB by updateTerminator(),
+ // so we first remove any instruction that already has an index.
+- if (Indexes->hasIndex(I))
+- Indexes->removeMachineInstrFromMaps(I);
+- Indexes->insertMachineInstrInMaps(I);
++ if (Indexes->hasIndex(&*I))
++ Indexes->removeMachineInstrFromMaps(&*I);
++ Indexes->insertMachineInstrInMaps(&*I);
+ }
+ }
+ }
+@@ -811,7 +810,7 @@
+
+ // Inherit live-ins from the successor
+ for (MachineBasicBlock::livein_iterator I = Succ->livein_begin(),
+- E = Succ->livein_end(); I != E; ++I)
++ E = Succ->livein_end(); I != E; ++I)
+ NMBB->addLiveIn(*I);
+
+ // Update LiveVariables.
+@@ -824,7 +823,7 @@
+ if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
+ continue;
+ if (TargetRegisterInfo::isVirtualRegister(Reg))
+- LV->getVarInfo(Reg).Kills.push_back(I);
++ LV->getVarInfo(Reg).Kills.push_back(&*I);
+ DEBUG(dbgs() << "Restored terminator kill: " << *I);
+ break;
+ }
+@@ -943,7 +942,7 @@
+
+ MachineBasicBlock::instr_iterator
+ MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
+- unbundleSingleMI(I);
++ unbundleSingleMI(&*I);
+ return Insts.erase(I);
+ }
+
+@@ -1038,12 +1037,12 @@
+
+ if (!DestA && !DestB) {
+ // Block falls through to successor.
+- DestA = FallThru;
+- DestB = FallThru;
++ DestA = &*FallThru;
++ DestB = &*FallThru;
+ } else if (DestA && !DestB) {
+ if (isCond)
+ // Block ends in conditional jump that falls through to successor.
+- DestB = FallThru;
++ DestB = &*FallThru;
+ } else {
+ assert(DestA && DestB && isCond &&
+ "CFG in a bad state. Cannot correct CFG edges");
+--- lib/CodeGen/MachineBlockFrequencyInfo.cpp 2014-06-26 15:52:05.000000000 -0700
++++ lib/CodeGen/MachineBlockFrequencyInfo.cpp 2015-12-06 20:30:07.075098190 -0800
+@@ -57,7 +57,7 @@
+
+ static inline
+ const NodeType *getEntryNode(const MachineBlockFrequencyInfo *G) {
+- return G->getFunction()->begin();
++ return &G->getFunction()->front();
+ }
+
+ static ChildIteratorType child_begin(const NodeType *N) {
+--- lib/CodeGen/MachineBlockPlacement.cpp 2015-01-03 09:58:24.000000000 -0800
++++ lib/CodeGen/MachineBlockPlacement.cpp 2015-12-06 20:45:33.550025788 -0800
+@@ -471,14 +471,14 @@
+ const BlockFilterSet *BlockFilter) {
+ for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
+ ++I) {
+- if (BlockFilter && !BlockFilter->count(I))
++ if (BlockFilter && !BlockFilter->count(&*I))
+ continue;
+- if (BlockToChain[I] != &PlacedChain) {
++ if (BlockToChain[&*I] != &PlacedChain) {
+ PrevUnplacedBlockIt = I;
+ // Now select the head of the chain to which the unplaced block belongs
+ // as the block to place. This will force the entire chain to be placed,
+ // and satisfies the requirements of merging chains.
+- return *BlockToChain[I]->begin();
++ return *BlockToChain[&*I]->begin();
+ }
+ }
+ return nullptr;
+@@ -878,9 +878,9 @@
+ // the assumptions of the remaining algorithm.
+ SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
+ for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
+- MachineBasicBlock *BB = FI;
+- BlockChain *Chain
+- = new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
++ MachineBasicBlock *BB = &*FI;
++ BlockChain *Chain =
++ new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
+ // Also, merge any blocks which we cannot reason about and must preserve
+ // the exact fallthrough behavior for.
+ for (;;) {
+@@ -890,7 +890,7 @@
+ break;
+
+ MachineFunction::iterator NextFI(std::next(FI));
+- MachineBasicBlock *NextBB = NextFI;
++ MachineBasicBlock *NextBB = &*NextFI;
+ // Ensure that the layout successor is a viable block, as we know that
+ // fallthrough is a possibility.
+ assert(NextFI != FE && "Can't fallthrough past the last block.");
+@@ -944,8 +944,9 @@
+ // Crash at the end so we get all of the debugging output first.
+ bool BadFunc = false;
+ FunctionBlockSetType FunctionBlockSet;
+- for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
+- FunctionBlockSet.insert(FI);
++
++ for (MachineBasicBlock &MBB : F)
++ FunctionBlockSet.insert(&MBB);
+
+ for (BlockChain::iterator BCI = FunctionChain.begin(),
+ BCE = FunctionChain.end();
+@@ -969,21 +970,19 @@
+
+ // Splice the blocks into place.
+ MachineFunction::iterator InsertPos = F.begin();
+- for (BlockChain::iterator BI = FunctionChain.begin(),
+- BE = FunctionChain.end();
+- BI != BE; ++BI) {
+- DEBUG(dbgs() << (BI == FunctionChain.begin() ? "Placing chain "
++ for (MachineBasicBlock *BI : FunctionChain) {
++ DEBUG(dbgs() << (BI == *FunctionChain.begin() ? "Placing chain "
+ : " ... ")
+- << getBlockName(*BI) << "\n");
+- if (InsertPos != MachineFunction::iterator(*BI))
+- F.splice(InsertPos, *BI);
++ << getBlockName(BI) << "\n");
++ if (InsertPos != MachineFunction::iterator(BI))
++ F.splice(InsertPos, BI->getIterator());
+ else
+ ++InsertPos;
+
+ // Update the terminator of the previous block.
+- if (BI == FunctionChain.begin())
++ if (BI == *FunctionChain.begin())
+ continue;
+- MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(*BI));
++ MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(BI));
+
+ // FIXME: It would be awesome of updateTerminator would just return rather
+ // than assert when the branch cannot be analyzed in order to remove this
+@@ -1002,7 +1001,7 @@
+ // is mistakenly pointing to "*BI".
+ //
+ bool needUpdateBr = true;
+- if (!Cond.empty() && (!FBB || FBB == *BI)) {
++ if (!Cond.empty() && (!FBB || FBB == BI)) {
+ PrevBB->updateTerminator();
+ needUpdateBr = false;
+ Cond.clear();
+@@ -1050,7 +1049,7 @@
+ return; // Empty chain.
+
+ const BranchProbability ColdProb(1, 5); // 20%
+- BlockFrequency EntryFreq = MBFI->getBlockFreq(F.begin());
++ BlockFrequency EntryFreq = MBFI->getBlockFreq(&F.front());
+ BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
+ for (BlockChain::iterator BI = std::next(FunctionChain.begin()),
+ BE = FunctionChain.end();
+@@ -1182,7 +1181,7 @@
+ MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
+
+ for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
+- BlockFrequency BlockFreq = MBFI->getBlockFreq(I);
++ BlockFrequency BlockFreq = MBFI->getBlockFreq(&*I);
+ Statistic &NumBranches = (I->succ_size() > 1) ? NumCondBranches
+ : NumUncondBranches;
+ Statistic &BranchTakenFreq = (I->succ_size() > 1) ? CondBranchTakenFreq
+@@ -1194,7 +1193,8 @@
+ if (I->isLayoutSuccessor(*SI))
+ continue;
+
+- BlockFrequency EdgeFreq = BlockFreq * MBPI->getEdgeProbability(I, *SI);
++ BlockFrequency EdgeFreq =
++ BlockFreq * MBPI->getEdgeProbability(&*I, *SI);
+ ++NumBranches;
+ BranchTakenFreq += EdgeFreq.getFrequency();
+ }
+--- lib/CodeGen/MachineFunction.cpp 2015-01-12 16:48:10.000000000 -0800
++++ lib/CodeGen/MachineFunction.cpp 2015-12-06 20:48:05.529036618 -0800
+@@ -144,7 +144,7 @@
+ if (MBB == nullptr)
+ MBBI = begin();
+ else
+- MBBI = MBB;
++ MBBI = MBB->getIterator();
+
+ // Figure out the block number this should have.
+ unsigned BlockNo = 0;
+@@ -164,7 +164,7 @@
+ if (MBBNumbering[BlockNo])
+ MBBNumbering[BlockNo]->setNumber(-1);
+
+- MBBNumbering[BlockNo] = MBBI;
++ MBBNumbering[BlockNo] = &*MBBI;
+ MBBI->setNumber(BlockNo);
+ }
+ }
+--- lib/CodeGen/MachineInstr.cpp 2014-12-09 10:38:53.000000000 -0800
++++ lib/CodeGen/MachineInstr.cpp 2015-12-06 21:23:40.823649137 -0800
+@@ -825,7 +825,8 @@
+
+ bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
+ assert(!isBundledWithPred() && "Must be called on bundle header");
+- for (MachineBasicBlock::const_instr_iterator MII = this;; ++MII) {
++ for (MachineBasicBlock::const_instr_iterator MII = getIterator();
++ /* empty */ ; ++MII) {
+ if (MII->getDesc().getFlags() & Mask) {
+ if (Type == AnyInBundle)
+ return true;
+@@ -849,13 +850,13 @@
+
+ if (isBundle()) {
+ // Both instructions are bundles, compare MIs inside the bundle.
+- MachineBasicBlock::const_instr_iterator I1 = *this;
++ MachineBasicBlock::const_instr_iterator I1 = getIterator();
+ MachineBasicBlock::const_instr_iterator E1 = getParent()->instr_end();
+- MachineBasicBlock::const_instr_iterator I2 = *Other;
++ MachineBasicBlock::const_instr_iterator I2 = Other->getIterator();
+ MachineBasicBlock::const_instr_iterator E2= Other->getParent()->instr_end();
+ while (++I1 != E1 && I1->isInsideBundle()) {
+ ++I2;
+- if (I2 == E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(I2, Check))
++ if (I2 == E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(&*I2, Check))
+ return false;
+ }
+ }
+@@ -961,7 +962,7 @@
+ void MachineInstr::bundleWithPred() {
+ assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
+ setFlag(BundledPred);
+- MachineBasicBlock::instr_iterator Pred = this;
++ MachineBasicBlock::instr_iterator Pred = getIterator();
+ --Pred;
+ assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
+ Pred->setFlag(BundledSucc);
+@@ -970,7 +971,7 @@
+ void MachineInstr::bundleWithSucc() {
+ assert(!isBundledWithSucc() && "MI is already bundled with its successor");
+ setFlag(BundledSucc);
+- MachineBasicBlock::instr_iterator Succ = this;
++ MachineBasicBlock::instr_iterator Succ = getIterator();
+ ++Succ;
+ assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
+ Succ->setFlag(BundledPred);
+@@ -979,7 +980,7 @@
+ void MachineInstr::unbundleFromPred() {
+ assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
+ clearFlag(BundledPred);
+- MachineBasicBlock::instr_iterator Pred = this;
++ MachineBasicBlock::instr_iterator Pred = getIterator();
+ --Pred;
+ assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
+ Pred->clearFlag(BundledSucc);
+@@ -988,7 +989,7 @@
+ void MachineInstr::unbundleFromSucc() {
+ assert(isBundledWithSucc() && "MI isn't bundled with its successor");
+ clearFlag(BundledSucc);
+- MachineBasicBlock::instr_iterator Succ = this;
++ MachineBasicBlock::instr_iterator Succ = getIterator();
+ ++Succ;
+ assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
+ Succ->clearFlag(BundledPred);
+@@ -1125,7 +1126,7 @@
+ /// Return the number of instructions inside the MI bundle, not counting the
+ /// header instruction.
+ unsigned MachineInstr::getBundleSize() const {
+- MachineBasicBlock::const_instr_iterator I = this;
++ MachineBasicBlock::const_instr_iterator I = getIterator();
+ unsigned Size = 0;
+ while (I->isBundledWithSucc())
+ ++Size, ++I;
+--- lib/CodeGen/MachineLoopInfo.cpp 2014-03-02 04:27:27.000000000 -0800
++++ lib/CodeGen/MachineLoopInfo.cpp 2015-12-06 21:26:39.722845395 -0800
+@@ -50,11 +50,11 @@
+ MachineBasicBlock *TopMBB = getHeader();
+ MachineFunction::iterator Begin = TopMBB->getParent()->begin();
+ if (TopMBB != Begin) {
+- MachineBasicBlock *PriorMBB = std::prev(MachineFunction::iterator(TopMBB));
++ MachineBasicBlock *PriorMBB = &*std::prev(TopMBB->getIterator());
+ while (contains(PriorMBB)) {
+ TopMBB = PriorMBB;
+ if (TopMBB == Begin) break;
+- PriorMBB = std::prev(MachineFunction::iterator(TopMBB));
++ PriorMBB = &*std::prev(TopMBB->getIterator());
+ }
+ }
+ return TopMBB;
+@@ -64,11 +64,11 @@
+ MachineBasicBlock *BotMBB = getHeader();
+ MachineFunction::iterator End = BotMBB->getParent()->end();
+ if (BotMBB != std::prev(End)) {
+- MachineBasicBlock *NextMBB = std::next(MachineFunction::iterator(BotMBB));
++ MachineBasicBlock *NextMBB = &*std::next(BotMBB->getIterator());
+ while (contains(NextMBB)) {
+ BotMBB = NextMBB;
+ if (BotMBB == std::next(MachineFunction::iterator(BotMBB))) break;
+- NextMBB = std::next(MachineFunction::iterator(BotMBB));
++ NextMBB = &*std::next(BotMBB->getIterator());
+ }
+ }
+ return BotMBB;
+--- lib/CodeGen/MachineScheduler.cpp 2014-12-12 20:52:04.000000000 -0800
++++ lib/CodeGen/MachineScheduler.cpp 2015-12-06 21:37:05.936122225 -0800
+@@ -391,7 +391,7 @@
+ for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
+ MBB != MBBEnd; ++MBB) {
+
+- Scheduler.startBlock(MBB);
++ Scheduler.startBlock(&*MBB);
+
+ #ifndef NDEBUG
+ if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
+@@ -420,7 +420,7 @@
+
+ // Avoid decrementing RegionEnd for blocks with no terminator.
+ if (RegionEnd != MBB->end() ||
+- isSchedBoundary(std::prev(RegionEnd), MBB, MF, TII, IsPostRA)) {
++ isSchedBoundary(std::prev(RegionEnd), &*MBB, MF, TII, IsPostRA)) {
+ --RegionEnd;
+ // Count the boundary instruction.
+ --RemainingInstrs;
+@@ -431,14 +431,14 @@
+ unsigned NumRegionInstrs = 0;
+ MachineBasicBlock::iterator I = RegionEnd;
+ for(;I != MBB->begin(); --I, --RemainingInstrs) {
+- if (isSchedBoundary(std::prev(I), MBB, MF, TII, IsPostRA))
++ if (isSchedBoundary(std::prev(I), &*MBB, MF, TII, IsPostRA))
+ break;
+ if (!I->isDebugValue())
+ ++NumRegionInstrs;
+ }
+ // Notify the scheduler of the region, even if we may skip scheduling
+ // it. Perhaps it still needs to be bundled.
+- Scheduler.enterRegion(MBB, I, RegionEnd, NumRegionInstrs);
++ Scheduler.enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs);
+
+ // Skip empty scheduling regions (0 or 1 schedulable instructions).
+ if (I == RegionEnd || I == std::prev(RegionEnd)) {
+@@ -478,7 +478,7 @@
+ if (Scheduler.isPostRA()) {
+ // FIXME: Ideally, no further passes should rely on kill flags. However,
+ // thumb2 size reduction is currently an exception.
+- Scheduler.fixupKills(MBB);
++ Scheduler.fixupKills(&*MBB);
+ }
+ }
+ Scheduler.finalizeSchedule();
+--- lib/CodeGen/MachineVerifier.cpp 2014-12-11 11:41:51.000000000 -0800
++++ lib/CodeGen/MachineVerifier.cpp 2015-12-06 22:06:08.770556953 -0800
+@@ -317,7 +317,7 @@
+ visitMachineFunctionBefore();
+ for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
+ MFI!=MFE; ++MFI) {
+- visitMachineBasicBlockBefore(MFI);
++ visitMachineBasicBlockBefore(&*MFI);
+ // Keep track of the current bundle header.
+ const MachineInstr *CurBundle = nullptr;
+ // Do we expect the next instruction to be part of the same bundle?
+@@ -325,8 +325,8 @@
+
+ for (MachineBasicBlock::const_instr_iterator MBBI = MFI->instr_begin(),
+ MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI) {
+- if (MBBI->getParent() != MFI) {
+- report("Bad instruction parent pointer", MFI);
++ if (MBBI->getParent() != &*MFI) {
++ report("Bad instruction parent pointer", &*MFI);
+ *OS << "Instruction: " << *MBBI;
+ continue;
+ }
+@@ -334,33 +334,44 @@
+ // Check for consistent bundle flags.
+ if (InBundle && !MBBI->isBundledWithPred())
+ report("Missing BundledPred flag, "
+- "BundledSucc was set on predecessor", MBBI);
++ "BundledSucc was set on predecessor", &*MBBI);
+ if (!InBundle && MBBI->isBundledWithPred())
+ report("BundledPred flag is set, "
+- "but BundledSucc not set on predecessor", MBBI);
++ "but BundledSucc not set on predecessor", &*MBBI);
+
+ // Is this a bundle header?
+ if (!MBBI->isInsideBundle()) {
+ if (CurBundle)
+ visitMachineBundleAfter(CurBundle);
+- CurBundle = MBBI;
++ CurBundle = &*MBBI;
+ visitMachineBundleBefore(CurBundle);
+ } else if (!CurBundle)
+- report("No bundle header", MBBI);
+- visitMachineInstrBefore(MBBI);
+- for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I)
+- visitMachineOperand(&MBBI->getOperand(I), I);
+- visitMachineInstrAfter(MBBI);
++ report("No bundle header", &*MBBI);
++
++ visitMachineInstrBefore(&*MBBI);
++
++ for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
++ const MachineInstr &MI = *MBBI;
++ const MachineOperand &Op = MI.getOperand(I);
++ if (Op.getParent() != &MI)
++ report("Instruction has operand with wrong parent set", &MI);
++
++ visitMachineOperand(&Op, I);
++ }
++
++ visitMachineInstrAfter(&*MBBI);
+
+ // Was this the last bundled instruction?
+ InBundle = MBBI->isBundledWithSucc();
+ }
++
+ if (CurBundle)
+ visitMachineBundleAfter(CurBundle);
+ if (InBundle)
+ report("BundledSucc flag set on last instruction in block", &MFI->back());
+- visitMachineBasicBlockAfter(MFI);
++ visitMachineBasicBlockAfter(&*MFI);
+ }
++
+ visitMachineFunctionAfter();
+
+ if (OutFile)
+@@ -573,7 +584,7 @@
+ // check whether its answers match up with reality.
+ if (!TBB && !FBB) {
+ // Block falls through to its successor.
+- MachineFunction::const_iterator MBBI = MBB;
++ MachineFunction::const_iterator MBBI = MBB->getIterator();
+ ++MBBI;
+ if (MBBI == MF->end()) {
+ // It's possible that the block legitimately ends with a noreturn
+@@ -586,7 +597,7 @@
+ } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
+ report("MBB exits via unconditional fall-through but doesn't have "
+ "exactly one CFG successor!", MBB);
+- } else if (!MBB->isSuccessor(MBBI)) {
++ } else if (!MBB->isSuccessor(&*MBBI)) {
+ report("MBB exits via unconditional fall-through but its successor "
+ "differs from its CFG successor!", MBB);
+ }
+@@ -624,7 +635,7 @@
+ }
+ } else if (TBB && !FBB && !Cond.empty()) {
+ // Block conditionally branches somewhere, otherwise falls through.
+- MachineFunction::const_iterator MBBI = MBB;
++ MachineFunction::const_iterator MBBI = MBB->getIterator();
+ ++MBBI;
+ if (MBBI == MF->end()) {
+ report("MBB conditionally falls through out of function!", MBB);
+@@ -639,7 +650,7 @@
+ } else if (MBB->succ_size() != 2) {
+ report("MBB exits via conditional branch/fall-through but doesn't have "
+ "exactly two CFG successors!", MBB);
+- } else if (!matchPair(MBB->succ_begin(), TBB, MBBI)) {
++ } else if (!matchPair(MBB->succ_begin(), TBB, &*MBBI)) {
+ report("MBB exits via conditional branch/fall-through but the CFG "
+ "successors don't match the actual successors!", MBB);
+ }
+@@ -1585,7 +1596,7 @@
+ }
+
+ // Now check all the basic blocks in this live segment.
+- MachineFunction::const_iterator MFI = MBB;
++ MachineFunction::const_iterator MFI = MBB->getIterator();
+ // Is this live segment the beginning of a non-PHIDef VN?
+ if (S.start == VNI->def && !VNI->isPHIDef()) {
+ // Not live-in to any blocks.
+@@ -1595,7 +1606,7 @@
+ ++MFI;
+ }
+ for (;;) {
+- assert(LiveInts->isLiveInToMBB(LR, MFI));
++ assert(LiveInts->isLiveInToMBB(LR, &*MFI));
+ // We don't know how to track physregs into a landing pad.
+ if (!TargetRegisterInfo::isVirtualRegister(Reg) &&
+ MFI->isLandingPad()) {
+@@ -1607,7 +1618,7 @@
+
+ // Is VNI a PHI-def in the current block?
+ bool IsPHI = VNI->isPHIDef() &&
+- VNI->def == LiveInts->getMBBStartIdx(MFI);
++ VNI->def == LiveInts->getMBBStartIdx(&*MFI);
+
+ // Check that VNI is live-out of all predecessors.
+ for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
+@@ -1620,7 +1631,7 @@
+ report("Register not marked live out of predecessor", *PI, LR, Reg,
+ LaneMask);
+ *OS << "Valno #" << VNI->id << " live into BB#" << MFI->getNumber()
+- << '@' << LiveInts->getMBBStartIdx(MFI) << ", not live before "
++ << '@' << LiveInts->getMBBStartIdx(&*MFI) << ", not live before "
+ << PEnd << '\n';
+ continue;
+ }
+@@ -1632,7 +1643,7 @@
+ *OS << "Valno #" << PVNI->id << " live out of BB#"
+ << (*PI)->getNumber() << '@' << PEnd
+ << "\nValno #" << VNI->id << " live into BB#" << MFI->getNumber()
+- << '@' << LiveInts->getMBBStartIdx(MFI) << '\n';
++ << '@' << LiveInts->getMBBStartIdx(&*MFI) << '\n';
+ }
+ }
+ if (&*MFI == EndMBB)
+--- lib/CodeGen/Passes.cpp 2015-02-11 16:29:01.000000000 -0800
++++ lib/CodeGen/Passes.cpp 2016-01-23 20:25:56.000000000 -0800
+@@ -83,10 +83,13 @@
+ static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
+ cl::desc("Verify generated machine code"),
+ cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=nullptr));
++
++static std::string PMIInitString("option-unspecified");
+ static cl::opt<std::string>
+ PrintMachineInstrs("print-machineinstrs", cl::ValueOptional,
+ cl::desc("Print machine instrs"),
+- cl::value_desc("pass-name"), cl::init("option-unspecified"));
++ cl::value_desc("pass-name"),
++ cl::init(PMIInitString));
+
+ // Temporary option to allow experimenting with MachineScheduler as a post-RA
+ // scheduler. Targets can "properly" enable this with
+--- lib/CodeGen/PostRASchedulerList.cpp 2014-10-29 08:23:11.000000000 -0700
++++ lib/CodeGen/PostRASchedulerList.cpp 2016-01-23 20:26:45.000000000 -0800
+@@ -58,11 +58,13 @@
+ EnablePostRAScheduler("post-RA-scheduler",
+ cl::desc("Enable scheduling after register allocation"),
+ cl::init(false), cl::Hidden);
++
++static std::string NoneString("none");
+ static cl::opt<std::string>
+ EnableAntiDepBreaking("break-anti-dependencies",
+ cl::desc("Break post-RA scheduling anti-dependencies: "
+ "\"critical\", \"all\", or \"none\""),
+- cl::init("none"), cl::Hidden);
++ cl::init(NoneString), cl::Hidden);
+
+ // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
+ static cl::opt<int>
+@@ -318,7 +320,7 @@
+ #endif
+
+ // Initialize register live-range state for scheduling in this block.
+- Scheduler.startBlock(MBB);
++ Scheduler.startBlock(&*MBB);
+
+ // Schedule each sequence of instructions not interrupted by a label
+ // or anything else that effectively needs to shut down scheduling.
+@@ -330,8 +332,8 @@
+ // Calls are not scheduling boundaries before register allocation, but
+ // post-ra we don't gain anything by scheduling across calls since we
+ // don't need to worry about register pressure.
+- if (MI->isCall() || TII->isSchedulingBoundary(MI, MBB, Fn)) {
+- Scheduler.enterRegion(MBB, I, Current, CurrentCount - Count);
++ if (MI->isCall() || TII->isSchedulingBoundary(MI, &*MBB, Fn)) {
++ Scheduler.enterRegion(&*MBB, I, Current, CurrentCount - Count);
+ Scheduler.setEndIndex(CurrentCount);
+ Scheduler.schedule();
+ Scheduler.exitRegion();
+@@ -347,7 +349,7 @@
+ assert(Count == 0 && "Instruction count mismatch!");
+ assert((MBB->begin() == Current || CurrentCount != 0) &&
+ "Instruction count mismatch!");
+- Scheduler.enterRegion(MBB, MBB->begin(), Current, CurrentCount);
++ Scheduler.enterRegion(&*MBB, MBB->begin(), Current, CurrentCount);
+ Scheduler.setEndIndex(CurrentCount);
+ Scheduler.schedule();
+ Scheduler.exitRegion();
+@@ -357,7 +359,7 @@
+ Scheduler.finishBlock();
+
+ // Update register kills
+- Scheduler.fixupKills(MBB);
++ Scheduler.fixupKills(&*MBB);
+ }
+
+ return true;
+--- lib/CodeGen/ProcessImplicitDefs.cpp 2014-08-04 19:39:49.000000000 -0700
++++ lib/CodeGen/ProcessImplicitDefs.cpp 2015-12-07 06:32:25.399048598 -0800
+@@ -96,11 +96,11 @@
+
+ // This is a physreg implicit-def.
+ // Look for the first instruction to use or define an alias.
+- MachineBasicBlock::instr_iterator UserMI = MI;
++ MachineBasicBlock::instr_iterator UserMI = MI->getIterator();
+ MachineBasicBlock::instr_iterator UserE = MI->getParent()->instr_end();
+ bool Found = false;
+ for (++UserMI; UserMI != UserE; ++UserMI) {
+- for (MIOperands MO(UserMI); MO.isValid(); ++MO) {
++ for (MIOperands MO(&*UserMI); MO.isValid(); ++MO) {
+ if (!MO->isReg())
+ continue;
+ unsigned UserReg = MO->getReg();
+@@ -151,7 +151,7 @@
+ for (MachineBasicBlock::instr_iterator MBBI = MFI->instr_begin(),
+ MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI)
+ if (MBBI->isImplicitDef())
+- WorkList.insert(MBBI);
++ WorkList.insert(&*MBBI);
+
+ if (WorkList.empty())
+ continue;
+--- lib/CodeGen/PrologEpilogInserter.cpp 2015-01-12 16:48:10.000000000 -0800
++++ lib/CodeGen/PrologEpilogInserter.cpp 2015-12-07 06:37:25.905435777 -0800
+@@ -94,13 +94,11 @@
+ return;
+
+ // Save refs to entry and return blocks.
+- EntryBlock = Fn.begin();
+- for (MachineFunction::iterator MBB = Fn.begin(), E = Fn.end();
+- MBB != E; ++MBB)
+- if (isReturnBlock(MBB))
+- ReturnBlocks.push_back(MBB);
+-
+- return;
++ EntryBlock = &Fn.front();
++ for (MachineBasicBlock &MBB : Fn) {
++ if (isReturnBlock(&MBB))
++ ReturnBlocks.push_back(&MBB);
++ }
+ }
+
+ /// StackObjSet - A set of stack object indexes
+@@ -728,11 +726,11 @@
+
+ // Handle the unreachable blocks.
+ for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
+- if (Reachable.count(BB))
++ if (Reachable.count(&*BB))
+ // Already handled in DFS traversal.
+ continue;
+ int SPAdj = 0;
+- replaceFrameIndices(BB, Fn, SPAdj);
++ replaceFrameIndices(&*BB, Fn, SPAdj);
+ }
+ }
+
+@@ -873,7 +871,7 @@
+ // Run through the instructions and find any virtual registers.
+ for (MachineFunction::iterator BB = Fn.begin(),
+ E = Fn.end(); BB != E; ++BB) {
+- RS->enterBasicBlock(BB);
++ RS->enterBasicBlock(&*BB);
+
+ int SPAdj = 0;
+
+@@ -922,7 +920,7 @@
+ assert (ScratchReg && "Missing scratch register!");
+ MachineRegisterInfo &MRI = Fn.getRegInfo();
+ Fn.getRegInfo().replaceRegWith(Reg, ScratchReg);
+-
++
+ // Make sure MRI now accounts this register as used.
+ MRI.setPhysRegUsed(ScratchReg);
+
+@@ -938,7 +936,7 @@
+ // problem because we need the spill code before I: Move I to just
+ // prior to J.
+ if (I != std::prev(J)) {
+- BB->splice(J, BB, I);
++ BB->splice(J, &*BB, I);
+
+ // Before we move I, we need to prepare the RS to visit I again.
+ // Specifically, RS will assert if it sees uses of registers that
+--- lib/CodeGen/RegisterCoalescer.cpp 2015-01-14 03:23:27.000000000 -0800
++++ lib/CodeGen/RegisterCoalescer.cpp 2015-12-07 06:39:22.414657202 -0800
+@@ -2669,7 +2669,7 @@
+ std::vector<MBBPriorityInfo> MBBs;
+ MBBs.reserve(MF->size());
+ for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
+- MachineBasicBlock *MBB = I;
++ MachineBasicBlock *MBB = &*I;
+ MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB),
+ JoinSplitEdges && isSplitEdge(MBB)));
+ }
+--- lib/CodeGen/SelectionDAG/DAGCombiner.cpp 2015-04-01 17:15:35.000000000 -0700
++++ lib/CodeGen/SelectionDAG/DAGCombiner.cpp 2015-12-07 08:35:37.075981457 -0800
+@@ -1163,7 +1163,7 @@
+ // Add all the dag nodes to the worklist.
+ for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
+ E = DAG.allnodes_end(); I != E; ++I)
+- AddToWorklist(I);
++ AddToWorklist(&*I);
+
+ // Create a dummy node (which is not added to allnodes), that adds a reference
+ // to the root node, preventing it from being deleted, and tracking any
+--- lib/CodeGen/SelectionDAG/FastISel.cpp 2015-04-29 07:54:57.000000000 -0700
++++ lib/CodeGen/SelectionDAG/FastISel.cpp 2015-12-07 08:37:53.997786920 -0800
+@@ -116,9 +116,9 @@
+ for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(),
+ E = FuncInfo.Fn->arg_end();
+ I != E; ++I) {
+- DenseMap<const Value *, unsigned>::iterator VI = LocalValueMap.find(I);
++ DenseMap<const Value *, unsigned>::iterator VI = LocalValueMap.find(&*I);
+ assert(VI != LocalValueMap.end() && "Missed an argument?");
+- FuncInfo.ValueMap[I] = VI->second;
++ FuncInfo.ValueMap[&*I] = VI->second;
+ }
+ return true;
+ }
+--- lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp 2014-12-02 10:50:36.000000000 -0800
++++ lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp 2015-12-07 08:44:06.691399075 -0800
+@@ -130,7 +130,7 @@
+
+ // Look for inline asm that clobbers the SP register.
+ if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
+- ImmutableCallSite CS(I);
++ ImmutableCallSite CS(&*I);
+ if (isa<InlineAsm>(CS.getCalledValue())) {
+ unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
+ std::vector<TargetLowering::AsmOperandInfo> Ops =
+@@ -167,10 +167,10 @@
+
+ // Mark values used outside their block as exported, by allocating
+ // a virtual register for them.
+- if (isUsedOutsideOfDefiningBlock(I))
++ if (isUsedOutsideOfDefiningBlock(&*I))
+ if (!isa<AllocaInst>(I) ||
+ !StaticAllocaMap.count(cast<AllocaInst>(I)))
+- InitializeRegForValue(I);
++ InitializeRegForValue(&*I);
+
+ // Collect llvm.dbg.declare information. This is done now instead of
+ // during the initial isel pass through the IR so that it is done
+@@ -204,15 +204,15 @@
+ }
+
+ // Decide the preferred extend type for a value.
+- PreferredExtendType[I] = getPreferredExtendForValue(I);
++ PreferredExtendType[&*I] = getPreferredExtendForValue(&*I);
+ }
+
+ // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
+ // also creates the initial PHI MachineInstrs, though none of the input
+ // operands are populated.
+ for (BB = Fn->begin(); BB != EB; ++BB) {
+- MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
+- MBBMap[BB] = MBB;
++ MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(&*BB);
++ MBBMap[&*BB] = MBB;
+ MF->push_back(MBB);
+
+ // Transfer the address-taken flag. This is necessary because there could
+--- lib/CodeGen/SelectionDAG/LegalizeDAG.cpp 2015-01-13 17:35:17.000000000 -0800
++++ lib/CodeGen/SelectionDAG/LegalizeDAG.cpp 2015-12-07 08:49:07.697376637 -0800
+@@ -4326,7 +4326,7 @@
+ for (auto NI = allnodes_end(); NI != allnodes_begin();) {
+ --NI;
+
+- SDNode *N = NI;
++ SDNode *N = &*NI;
+ if (N->use_empty() && N != getRoot().getNode()) {
+ ++NI;
+ DeleteNode(N);
+--- lib/CodeGen/SelectionDAG/LegalizeTypes.cpp 2014-12-02 14:01:00.000000000 -0800
++++ lib/CodeGen/SelectionDAG/LegalizeTypes.cpp 2015-12-07 08:56:21.562944470 -0800
+@@ -77,10 +77,10 @@
+ E = DAG.allnodes_end(); I != E; ++I) {
+ // Remember nodes marked NewNode - they are subject to extra checking below.
+ if (I->getNodeId() == NewNode)
+- NewNodes.push_back(I);
++ NewNodes.push_back(&*I);
+
+ for (unsigned i = 0, e = I->getNumValues(); i != e; ++i) {
+- SDValue Res(I, i);
++ SDValue Res(&*I, i);
+ bool Failed = false;
+
+ unsigned Mapped = 0;
+@@ -128,7 +128,7 @@
+ dbgs() << "Unprocessed value in a map!";
+ Failed = true;
+ }
+- } else if (isTypeLegal(Res.getValueType()) || IgnoreNodeResults(I)) {
++ } else if (isTypeLegal(Res.getValueType()) || IgnoreNodeResults(&*I)) {
+ if (Mapped > 1) {
+ dbgs() << "Value with legal type was transformed!";
+ Failed = true;
+@@ -198,7 +198,7 @@
+ E = DAG.allnodes_end(); I != E; ++I) {
+ if (I->getNumOperands() == 0) {
+ I->setNodeId(ReadyToProcess);
+- Worklist.push_back(I);
++ Worklist.push_back(&*I);
+ } else {
+ I->setNodeId(Unanalyzed);
+ }
+@@ -406,7 +406,7 @@
+ bool Failed = false;
+
+ // Check that all result types are legal.
+- if (!IgnoreNodeResults(I))
++ if (!IgnoreNodeResults(&*I))
+ for (unsigned i = 0, NumVals = I->getNumValues(); i < NumVals; ++i)
+ if (!isTypeLegal(I->getValueType(i))) {
+ dbgs() << "Result type " << i << " illegal!\n";
+--- lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp 2015-02-12 15:51:24.000000000 -0800
++++ lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp 2015-12-07 09:08:20.015507523 -0800
+@@ -159,7 +159,7 @@
+ DAG.AssignTopologicalOrder();
+ for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
+ E = std::prev(DAG.allnodes_end()); I != std::next(E); ++I)
+- LegalizeOp(SDValue(I, 0));
++ LegalizeOp(SDValue(&*I, 0));
+
+ // Finally, it's possible the root changed. Get the new root.
+ SDValue OldRoot = DAG.getRoot();
+--- lib/CodeGen/SelectionDAG/ScheduleDAGFast.cpp 2014-11-18 23:49:26.000000000 -0800
++++ lib/CodeGen/SelectionDAG/ScheduleDAGFast.cpp 2015-12-07 09:09:27.427273648 -0800
+@@ -728,7 +728,7 @@
+ unsigned DAGSize = 0;
+ for (SelectionDAG::allnodes_iterator I = DAG->allnodes_begin(),
+ E = DAG->allnodes_end(); I != E; ++I) {
+- SDNode *N = I;
++ SDNode *N = &*I;
+
+ // Use node id to record degree.
+ unsigned Degree = N->use_size();
+--- lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp 2015-05-08 07:13:47.000000000 -0700
++++ lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp 2015-12-07 10:48:44.168405053 -0800
+@@ -1460,7 +1460,7 @@
+ }
+
+ // Create TmpBB after CurBB.
+- MachineFunction::iterator BBI = CurBB;
++ MachineFunction::iterator BBI(CurBB);
+ MachineFunction &MF = DAG.getMachineFunction();
+ MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
+ CurBB->getParent()->insert(++BBI, TmpBB);
+@@ -1575,9 +1575,9 @@
+
+ // Figure out which block is immediately after the current one.
+ MachineBasicBlock *NextBlock = nullptr;
+- MachineFunction::iterator BBI = BrMBB;
++ MachineFunction::iterator BBI(BrMBB);
+ if (++BBI != FuncInfo.MF->end())
+- NextBlock = BBI;
++ NextBlock = &*BBI;
+
+ if (I.isUnconditional()) {
+ // Update machine-CFG edges.
+@@ -1708,9 +1708,9 @@
+ // Set NextBlock to be the MBB immediately after the current one, if any.
+ // This is used to avoid emitting unnecessary branches to the next block.
+ MachineBasicBlock *NextBlock = nullptr;
+- MachineFunction::iterator BBI = SwitchBB;
++ MachineFunction::iterator BBI(SwitchBB);
+ if (++BBI != FuncInfo.MF->end())
+- NextBlock = BBI;
++ NextBlock = &*BBI;
+
+ // If the lhs block is the next block, invert the condition so that we can
+ // fall through to the lhs instead of the rhs block.
+@@ -1784,10 +1784,10 @@
+ // Set NextBlock to be the MBB immediately after the current one, if any.
+ // This is used to avoid emitting unnecessary branches to the next block.
+ MachineBasicBlock *NextBlock = nullptr;
+- MachineFunction::iterator BBI = SwitchBB;
++ MachineFunction::iterator BBI(SwitchBB);
+
+ if (++BBI != FuncInfo.MF->end())
+- NextBlock = BBI;
++ NextBlock = &*BBI;
+
+ SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
+ MVT::Other, CopyTo, CMP,
+@@ -1925,9 +1925,9 @@
+ // Set NextBlock to be the MBB immediately after the current one, if any.
+ // This is used to avoid emitting unnecessary branches to the next block.
+ MachineBasicBlock *NextBlock = nullptr;
+- MachineFunction::iterator BBI = SwitchBB;
++ MachineFunction::iterator BBI(SwitchBB);
+ if (++BBI != FuncInfo.MF->end())
+- NextBlock = BBI;
++ NextBlock = &*BBI;
+
+ MachineBasicBlock* MBB = B.Cases[0].ThisBB;
+
+@@ -1994,9 +1994,9 @@
+ // Set NextBlock to be the MBB immediately after the current one, if any.
+ // This is used to avoid emitting unnecessary branches to the next block.
+ MachineBasicBlock *NextBlock = nullptr;
+- MachineFunction::iterator BBI = SwitchBB;
++ MachineFunction::iterator BBI(SwitchBB);
+ if (++BBI != FuncInfo.MF->end())
+- NextBlock = BBI;
++ NextBlock = &*BBI;
+
+ if (NextMBB != NextBlock)
+ BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd,
+@@ -2104,10 +2104,10 @@
+
+ // Figure out which block is immediately after the current one.
+ MachineBasicBlock *NextBlock = nullptr;
+- MachineFunction::iterator BBI = CR.CaseBB;
++ MachineFunction::iterator BBI(CR.CaseBB);
+
+ if (++BBI != FuncInfo.MF->end())
+- NextBlock = BBI;
++ NextBlock = &*BBI;
+
+ BranchProbabilityInfo *BPI = FuncInfo.BPI;
+ // If any two of the cases has the same destination, and if one value
+@@ -2291,7 +2291,7 @@
+ MachineFunction *CurMF = FuncInfo.MF;
+
+ // Figure out which block is immediately after the current one.
+- MachineFunction::iterator BBI = CR.CaseBB;
++ MachineFunction::iterator BBI(CR.CaseBB);
+ ++BBI;
+
+ const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
+@@ -2377,7 +2377,7 @@
+ MachineFunction *CurMF = FuncInfo.MF;
+
+ // Figure out which block is immediately after the current one.
+- MachineFunction::iterator BBI = CR.CaseBB;
++ MachineFunction::iterator BBI(CR.CaseBB);
+ ++BBI;
+
+ Case& FrontCase = *CR.Range.first;
+@@ -2600,7 +2600,7 @@
+ BitTestInfo BTC;
+
+ // Figure out which block is immediately after the current one.
+- MachineFunction::iterator BBI = CR.CaseBB;
++ MachineFunction::iterator BBI(CR.CaseBB);
+ ++BBI;
+
+ const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
+@@ -7614,7 +7614,7 @@
+ if (FastISel)
+ return A->use_empty();
+
+- const BasicBlock *Entry = A->getParent()->begin();
++ const BasicBlock *Entry = &A->getParent()->front();
+ for (const User *U : A->users())
+ if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
+ return false; // Use not in entry block.
+@@ -7779,12 +7779,12 @@
+ // If this argument is unused then remember its value. It is used to generate
+ // debugging information.
+ if (I->use_empty() && NumValues) {
+- SDB->setUnusedArgValue(I, InVals[i]);
++ SDB->setUnusedArgValue(&*I, InVals[i]);
+
+ // Also remember any frame index for use in FastISel.
+ if (FrameIndexSDNode *FI =
+ dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
+- FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
++ FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex());
+ }
+
+ for (unsigned Val = 0; Val != NumValues; ++Val) {
+@@ -7814,18 +7814,18 @@
+ // Note down frame index.
+ if (FrameIndexSDNode *FI =
+ dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
+- FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
++ FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex());
+
+ SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
+ SDB->getCurSDLoc());
+
+- SDB->setValue(I, Res);
++ SDB->setValue(&*I, Res);
+ if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
+ if (LoadSDNode *LNode =
+ dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
+ if (FrameIndexSDNode *FI =
+ dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
+- FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
++ FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex());
+ }
+
+ // If this argument is live outside of the entry block, insert a copy from
+@@ -7837,13 +7837,13 @@
+ // uses with vregs.
+ unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
+ if (TargetRegisterInfo::isVirtualRegister(Reg)) {
+- FuncInfo->ValueMap[I] = Reg;
++ FuncInfo->ValueMap[&*I] = Reg;
+ continue;
+ }
+ }
+- if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
+- FuncInfo->InitializeRegForValue(I);
+- SDB->CopyToExportRegsIfNeeded(I);
++ if (!isOnlyUsedInEntryBlock(&*I, TM.Options.EnableFastISel)) {
++ FuncInfo->InitializeRegForValue(&*I);
++ SDB->CopyToExportRegsIfNeeded(&*I);
+ }
+ }
+
+@@ -7946,7 +7946,7 @@
+ // If SuccBB has not been created yet, create it.
+ if (!SuccMBB) {
+ MachineFunction *MF = ParentMBB->getParent();
+- MachineFunction::iterator BBI = ParentMBB;
++ MachineFunction::iterator BBI(ParentMBB);
+ SuccMBB = MF->CreateMachineBasicBlock(BB);
+ MF->insert(++BBI, SuccMBB);
+ }
+--- lib/CodeGen/SelectionDAG/SelectionDAGDumper.cpp 2014-12-04 01:40:44.000000000 -0800
++++ lib/CodeGen/SelectionDAG/SelectionDAGDumper.cpp 2015-12-07 11:02:44.434678105 -0800
+@@ -554,7 +554,7 @@
+
+ for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
+ I != E; ++I) {
+- const SDNode *N = I;
++ const SDNode *N = &*I;
+ if (!N->hasOneUse() && N != getRoot().getNode())
+ DumpNodes(N, 2, this);
+ }
+--- lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp 2015-06-14 08:38:10.000000000 -0700
++++ lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp 2015-12-07 11:43:29.120419077 -0800
+@@ -401,7 +401,7 @@
+
+ // Okay, we have to split this edge.
+ SplitCriticalEdge(Pred->getTerminator(),
+- GetSuccessorNumber(Pred, BB), SDISel, true);
++ GetSuccessorNumber(Pred, &*BB), SDISel, true);
+ goto ReprocessBlock;
+ }
+ }
+@@ -457,7 +457,7 @@
+ // If the first basic block in the function has live ins that need to be
+ // copied into vregs, emit the copies into the top of the block before
+ // emitting the code for the block.
+- MachineBasicBlock *EntryMBB = MF->begin();
++ MachineBasicBlock *EntryMBB = &MF->front();
+ const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
+ RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII);
+
+@@ -868,7 +868,7 @@
+ // graph) and preceding back toward the beginning (the entry
+ // node).
+ while (ISelPosition != CurDAG->allnodes_begin()) {
+- SDNode *Node = --ISelPosition;
++ SDNode *Node = &*--ISelPosition;
+ // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
+ // but there are currently some corner cases that it misses. Also, this
+ // makes it theoretically possible to disable the DAGCombiner.
+@@ -1085,7 +1085,8 @@
+ FuncInfo->VisitedBBs.insert(LLVMBB);
+ }
+
+- BasicBlock::const_iterator const Begin = LLVMBB->getFirstNonPHI();
++ BasicBlock::const_iterator const Begin =
++ LLVMBB->getFirstNonPHI()->getIterator();
+ BasicBlock::const_iterator const End = LLVMBB->end();
+ BasicBlock::const_iterator BI = End;
+
+@@ -1133,7 +1134,7 @@
+ unsigned NumFastIselRemaining = std::distance(Begin, End);
+ // Do FastISel on as many instructions as possible.
+ for (; BI != Begin; --BI) {
+- const Instruction *Inst = std::prev(BI);
++ const Instruction *Inst = &*std::prev(BI);
+
+ // If we no longer require this instruction, skip it.
+ if (isFoldedOrDeadInstruction(Inst, FuncInfo)) {
+@@ -1154,7 +1155,7 @@
+ // Try to fold the load if so.
+ const Instruction *BeforeInst = Inst;
+ while (BeforeInst != Begin) {
+- BeforeInst = std::prev(BasicBlock::const_iterator(BeforeInst));
++ BeforeInst = &*std::prev(BasicBlock::const_iterator(BeforeInst));
+ if (!isFoldedOrDeadInstruction(BeforeInst, FuncInfo))
+ break;
+ }
+@@ -1190,7 +1191,7 @@
+
+ bool HadTailCall = false;
+ MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
+- SelectBasicBlock(Inst, BI, HadTailCall);
++ SelectBasicBlock(Inst->getIterator(), BI, HadTailCall);
+
+ // If the call was emitted as a tail call, we're done with the block.
+ // We also need to delete any previously emitted instructions.
+--- lib/CodeGen/SelectionDAG/SelectionDAG.cpp 2015-02-17 13:57:20.000000000 -0800
++++ lib/CodeGen/SelectionDAG/SelectionDAG.cpp 2015-12-07 09:14:05.327228003 -0800
+@@ -618,7 +618,7 @@
+ // Add all obviously-dead nodes to the DeadNodes worklist.
+ for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
+ if (I->use_empty())
+- DeadNodes.push_back(I);
++ DeadNodes.push_back(&*I);
+
+ RemoveDeadNodes(DeadNodes);
+
+@@ -937,7 +937,7 @@
+ assert(&*AllNodes.begin() == &EntryNode);
+ AllNodes.remove(AllNodes.begin());
+ while (!AllNodes.empty())
+- DeallocateNode(AllNodes.begin());
++ DeallocateNode(&AllNodes.front());
+ }
+
+ BinarySDNode *SelectionDAG::GetBinarySDNode(unsigned Opcode, SDLoc DL,
+@@ -6139,13 +6139,15 @@
+ // Node Id fields for nodes At SortedPos and after will contain the
+ // count of outstanding operands.
+ for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
+- SDNode *N = I++;
++ SDNode *N = &*I;
++ ++I;
++
+ checkForCycles(N, this);
+ unsigned Degree = N->getNumOperands();
+ if (Degree == 0) {
+ // A node with no uses, add it to the result array immediately.
+ N->setNodeId(DAGSize++);
+- allnodes_iterator Q = N;
++ allnodes_iterator Q(N);
+ if (Q != SortedPos)
+ SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
+ assert(SortedPos != AllNodes.end() && "Overran node list");
+@@ -6159,7 +6161,7 @@
+ // Visit all the nodes. As we iterate, move nodes into sorted order,
+ // such that by the time the end is reached all nodes will be sorted.
+ for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
+- SDNode *N = I;
++ SDNode *N = &*I;
+ checkForCycles(N, this);
+ // N is in sorted position, so all its uses have one less operand
+ // that needs to be sorted.
+@@ -6183,7 +6185,7 @@
+ }
+ if (I == SortedPos) {
+ #ifndef NDEBUG
+- SDNode *S = ++I;
++ SDNode *S = &*++I;
+ dbgs() << "Overran sorted position:\n";
+ S->dumprFull(this); dbgs() << "\n";
+ dbgs() << "Checking if this is due to cycles\n";
+--- lib/CodeGen/ShadowStackGC.cpp 2014-11-13 14:55:19.000000000 -0800
++++ lib/CodeGen/ShadowStackGC.cpp 2015-12-07 06:47:52.372680302 -0800
+@@ -112,7 +112,8 @@
+ case 1:
+ // Find all 'return', 'resume', and 'unwind' instructions.
+ while (StateBB != StateE) {
+- BasicBlock *CurBB = StateBB++;
++ BasicBlock *CurBB = &*StateBB;
++ ++StateBB;
+
+ // Branches and invokes do not escape, only unwind, resume, and return
+ // do.
+@@ -120,7 +121,7 @@
+ if (!isa<ReturnInst>(TI) && !isa<ResumeInst>(TI))
+ continue;
+
+- Builder.SetInsertPoint(TI->getParent(), TI);
++ Builder.SetInsertPoint(TI);
+ return &Builder;
+ }
+
+@@ -164,7 +165,8 @@
+ // Split the basic block containing the function call.
+ BasicBlock *CallBB = CI->getParent();
+ BasicBlock *NewBB =
+- CallBB->splitBasicBlock(CI, CallBB->getName() + ".cont");
++ CallBB->splitBasicBlock(CI->getIterator(),
++ CallBB->getName() + ".cont");
+
+ // Remove the unconditional branch inserted at the end of CallBB.
+ CallBB->getInstList().pop_back();
+@@ -184,7 +186,7 @@
+ delete CI;
+ }
+
+- Builder.SetInsertPoint(RI->getParent(), RI);
++ Builder.SetInsertPoint(RI);
+ return &Builder;
+ }
+ }
+--- lib/CodeGen/SjLjEHPrepare.cpp 2014-11-18 23:49:26.000000000 -0800
++++ lib/CodeGen/SjLjEHPrepare.cpp 2015-12-07 06:54:48.366220128 -0800
+@@ -174,8 +174,8 @@
+ // values and replace the LPI with that aggregate.
+ Type *LPadType = LPI->getType();
+ Value *LPadVal = UndefValue::get(LPadType);
+- IRBuilder<> Builder(
+- std::next(BasicBlock::iterator(cast<Instruction>(SelVal))));
++ auto *SelI = cast<Instruction>(SelVal);
++ IRBuilder<> Builder(SelI->getParent(), std::next(SelI->getIterator()));
+ LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
+ LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
+
+@@ -186,7 +186,7 @@
+ /// it with all of the data that we know at this point.
+ Value *SjLjEHPrepare::setupFunctionContext(Function &F,
+ ArrayRef<LandingPadInst *> LPads) {
+- BasicBlock *EntryBB = F.begin();
++ BasicBlock *EntryBB = &F.front();
+
+ // Create an alloca for the incoming jump buffer ptr and the new jump buffer
+ // that needs to be restored on all exits from the function. This is an alloca
+@@ -195,12 +195,13 @@
+ unsigned Align =
+ TLI->getDataLayout()->getPrefTypeAlignment(FunctionContextTy);
+ FuncCtx = new AllocaInst(FunctionContextTy, nullptr, Align, "fn_context",
+- EntryBB->begin());
++ &EntryBB->front());
+
+ // Fill in the function context structure.
+ for (unsigned I = 0, E = LPads.size(); I != E; ++I) {
+ LandingPadInst *LPI = LPads[I];
+- IRBuilder<> Builder(LPI->getParent()->getFirstInsertionPt());
++ IRBuilder<> Builder(LPI->getParent(),
++ LPI->getParent()->getFirstInsertionPt());
+
+ // Reference the __data field.
+ Value *FCData = Builder.CreateConstGEP2_32(FuncCtx, 0, 2, "__data");
+@@ -253,13 +254,13 @@
+ // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
+ Value *TrueValue = ConstantInt::getTrue(F.getContext());
+ Value *UndefValue = UndefValue::get(Ty);
+- Instruction *SI = SelectInst::Create(TrueValue, AI, UndefValue,
++ Instruction *SI = SelectInst::Create(TrueValue, &*AI, UndefValue,
+ AI->getName() + ".tmp",
+- AfterAllocaInsPt);
++ &*AfterAllocaInsPt);
+ AI->replaceAllUsesWith(SI);
+
+ // Reset the operand, because it was clobbered by the RAUW above.
+- SI->setOperand(1, AI);
++ SI->setOperand(1, &*AI);
+ }
+ }
+
+@@ -274,7 +275,7 @@
+ // Ignore obvious cases we don't have to handle. In particular, most
+ // instructions either have no uses or only have a single use inside the
+ // current block. Ignore them quickly.
+- Instruction *Inst = II;
++ Instruction *Inst = &*II;
+ if (Inst->use_empty())
+ continue;
+ if (Inst->hasOneUse() &&
+@@ -355,7 +356,7 @@
+ DemotePHIToStack(PN);
+
+ // Move the landingpad instruction back to the top of the landing pad block.
+- LPI->moveBefore(UnwindBlock->begin());
++ LPI->moveBefore(&UnwindBlock->front());
+ }
+ }
+
+@@ -395,7 +396,7 @@
+
+ Value *FuncCtx =
+ setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
+- BasicBlock *EntryBB = F.begin();
++ BasicBlock *EntryBB = &F.front();
+ IRBuilder<> Builder(EntryBB->getTerminator());
+
+ // Get a reference to the jump buffer.
+@@ -467,7 +468,7 @@
+ continue;
+ }
+ Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
+- StackAddr->insertAfter(I);
++ StackAddr->insertAfter(&*I);
+ Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
+ StoreStackAddr->insertAfter(StackAddr);
+ }
+--- lib/CodeGen/SlotIndexes.cpp 2014-04-21 19:02:50.000000000 -0700
++++ lib/CodeGen/SlotIndexes.cpp 2015-12-07 07:32:28.357221215 -0800
+@@ -172,8 +172,8 @@
+ // optionally includes an additional position prior to MBB->begin(), indicated
+ // by the includeStart flag. This is done so that we can iterate MIs in a MBB
+ // in parallel with SlotIndexes, but there should be a better way to do this.
+- IndexList::iterator ListB = startIdx.listEntry();
+- IndexList::iterator ListI = endIdx.listEntry();
++ IndexList::iterator ListB = startIdx.listEntry()->getIterator();
++ IndexList::iterator ListI = endIdx.listEntry()->getIterator();
+ MachineBasicBlock::iterator MBBI = End;
+ bool pastStart = false;
+ while (ListI != ListB || MBBI != Begin || (includeStart && !pastStart)) {
+--- lib/CodeGen/SpillPlacement.cpp 2014-10-02 15:23:14.000000000 -0700
++++ lib/CodeGen/SpillPlacement.cpp 2015-12-07 07:33:14.076165375 -0800
+@@ -190,7 +190,7 @@
+ setThreshold(MBFI->getEntryFreq());
+ for (MachineFunction::iterator I = mf.begin(), E = mf.end(); I != E; ++I) {
+ unsigned Num = I->getNumber();
+- BlockFrequencies[Num] = MBFI->getBlockFreq(I);
++ BlockFrequencies[Num] = MBFI->getBlockFreq(&*I);
+ }
+
+ // We never change the function.
+--- lib/CodeGen/SplitKit.cpp 2014-12-10 15:07:54.000000000 -0800
++++ lib/CodeGen/SplitKit.cpp 2015-12-07 07:59:47.837252063 -0800
+@@ -176,10 +176,11 @@
+ UseE = UseSlots.end();
+
+ // Loop over basic blocks where CurLI is live.
+- MachineFunction::iterator MFI = LIS.getMBBFromIndex(LVI->start);
++ MachineFunction::iterator MFI =
++ LIS.getMBBFromIndex(LVI->start)->getIterator();
+ for (;;) {
+ BlockInfo BI;
+- BI.MBB = MFI;
++ BI.MBB = &*MFI;
+ SlotIndex Start, Stop;
+ std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
+
+@@ -259,7 +260,7 @@
+ if (LVI->start < Stop)
+ ++MFI;
+ else
+- MFI = LIS.getMBBFromIndex(LVI->start);
++ MFI = LIS.getMBBFromIndex(LVI->start)->getIterator();
+ }
+
+ assert(getNumLiveBlocks() == countLiveBlocks(CurLI) && "Bad block count");
+@@ -275,8 +276,9 @@
+ unsigned Count = 0;
+
+ // Loop over basic blocks where li is live.
+- MachineFunction::const_iterator MFI = LIS.getMBBFromIndex(LVI->start);
+- SlotIndex Stop = LIS.getMBBEndIdx(MFI);
++ MachineFunction::const_iterator MFI =
++ LIS.getMBBFromIndex(LVI->start)->getIterator();
++ SlotIndex Stop = LIS.getMBBEndIdx(&*MFI);
+ for (;;) {
+ ++Count;
+ LVI = li->advanceTo(LVI, Stop);
+@@ -284,7 +286,7 @@
+ return Count;
+ do {
+ ++MFI;
+- Stop = LIS.getMBBEndIdx(MFI);
++ Stop = LIS.getMBBEndIdx(&*MFI);
+ } while (Stop <= LVI->start);
+ }
+ }
+@@ -866,9 +868,11 @@
+ // This value has multiple defs in RegIdx, but it wasn't rematerialized,
+ // so the live range is accurate. Add live-in blocks in [Start;End) to the
+ // LiveInBlocks.
+- MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start);
++ MachineFunction::iterator MBB =
++ LIS.getMBBFromIndex(Start)->getIterator();
+ SlotIndex BlockStart, BlockEnd;
+- std::tie(BlockStart, BlockEnd) = LIS.getSlotIndexes()->getMBBRange(MBB);
++ std::tie(BlockStart, BlockEnd) =
++ LIS.getSlotIndexes()->getMBBRange(&*MBB);
+
+ // The first block may be live-in, or it may have its own def.
+ if (Start != BlockStart) {
+@@ -877,7 +881,7 @@
+ DEBUG(dbgs() << ':' << VNI->id << "*BB#" << MBB->getNumber());
+ // MBB has its own def. Is it also live-out?
+ if (BlockEnd <= End)
+- LRC.setLiveOutValue(MBB, VNI);
++ LRC.setLiveOutValue(&*MBB, VNI);
+
+ // Skip to the next block for live-in.
+ ++MBB;
+@@ -888,23 +892,23 @@
+ assert(Start <= BlockStart && "Expected live-in block");
+ while (BlockStart < End) {
+ DEBUG(dbgs() << ">BB#" << MBB->getNumber());
+- BlockEnd = LIS.getMBBEndIdx(MBB);
++ BlockEnd = LIS.getMBBEndIdx(&*MBB);
+ if (BlockStart == ParentVNI->def) {
+ // This block has the def of a parent PHI, so it isn't live-in.
+ assert(ParentVNI->isPHIDef() && "Non-phi defined at block start?");
+ VNInfo *VNI = LR.extendInBlock(BlockStart, std::min(BlockEnd, End));
+ assert(VNI && "Missing def for complex mapped parent PHI");
+ if (End >= BlockEnd)
+- LRC.setLiveOutValue(MBB, VNI); // Live-out as well.
++ LRC.setLiveOutValue(&*MBB, VNI); // Live-out as well.
+ } else {
+ // This block needs a live-in value. The last block covered may not
+ // be live-out.
+ if (End < BlockEnd)
+- LRC.addLiveInBlock(LR, MDT[MBB], End);
++ LRC.addLiveInBlock(LR, MDT[&*MBB], End);
+ else {
+ // Live-through, and we don't know the value.
+- LRC.addLiveInBlock(LR, MDT[MBB]);
+- LRC.setLiveOutValue(MBB, nullptr);
++ LRC.addLiveInBlock(LR, MDT[&*MBB]);
++ LRC.setLiveOutValue(&*MBB, nullptr);
+ }
+ }
+ BlockStart = BlockEnd;
+--- lib/CodeGen/StackMapLivenessAnalysis.cpp 2015-01-13 09:47:59.000000000 -0800
++++ lib/CodeGen/StackMapLivenessAnalysis.cpp 2015-12-07 08:03:47.966214485 -0800
+@@ -86,7 +86,7 @@
+ MBBI != MBBE; ++MBBI) {
+ DEBUG(dbgs() << "****** BB " << MBBI->getName() << " ******\n");
+ LiveRegs.init(TRI);
+- LiveRegs.addLiveOuts(MBBI);
++ LiveRegs.addLiveOuts(&*MBBI);
+ bool HasStackMap = false;
+ // Reverse iterate over all instructions and add the current live register
+ // set to an instruction if we encounter a patchpoint instruction.
+--- lib/CodeGen/StackProtector.cpp 2014-12-21 13:52:38.000000000 -0800
++++ lib/CodeGen/StackProtector.cpp 2015-12-07 08:06:06.725425403 -0800
+@@ -377,7 +377,8 @@
+ Value *StackGuardVar = nullptr; // The stack guard variable.
+
+ for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
+- BasicBlock *BB = I++;
++ BasicBlock *BB = &*I;
++ ++I;
+ ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
+ if (!RI)
+ continue;
+@@ -437,7 +438,7 @@
+ BasicBlock *FailBB = CreateFailBB();
+
+ // Split the basic block before the return instruction.
+- BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
++ BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
+
+ // Update the dominator tree if we need to.
+ if (DT && DT->isReachableFromEntry(BB)) {
+--- lib/CodeGen/TailDuplication.cpp 2014-08-04 19:39:49.000000000 -0700
++++ lib/CodeGen/TailDuplication.cpp 2015-12-07 08:11:12.192736388 -0800
+@@ -161,7 +161,7 @@
+
+ static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
+ for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
+- MachineBasicBlock *MBB = I;
++ MachineBasicBlock *MBB = &*I;
+ SmallSetVector<MachineBasicBlock*, 8> Preds(MBB->pred_begin(),
+ MBB->pred_end());
+ MachineBasicBlock::iterator MI = MBB->begin();
+@@ -322,7 +322,8 @@
+ }
+
+ for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
+- MachineBasicBlock *MBB = I++;
++ MachineBasicBlock *MBB = &*I;
++ ++I;
+
+ if (NumTails == TailDupLimit)
+ break;
+@@ -697,7 +698,7 @@
+ << "From simple Succ: " << *TailBB);
+
+ MachineBasicBlock *NewTarget = *TailBB->succ_begin();
+- MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(PredBB));
++ MachineBasicBlock *NextBB = &*std::next(PredBB->getIterator());
+
+ // Make PredFBB explicit.
+ if (PredCond.empty())
+@@ -855,7 +856,7 @@
+ // If TailBB was duplicated into all its predecessors except for the prior
+ // block, which falls through unconditionally, move the contents of this
+ // block into the prior block.
+- MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(TailBB));
++ MachineBasicBlock *PrevBB = &*std::prev(TailBB->getIterator());
+ MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
+ SmallVector<MachineOperand, 4> PriorCond;
+ // This has to check PrevBB->succ_size() because EH edges are ignored by
+--- lib/CodeGen/TwoAddressInstructionPass.cpp 2014-11-18 23:49:26.000000000 -0800
++++ lib/CodeGen/TwoAddressInstructionPass.cpp 2015-12-07 08:24:37.706267592 -0800
+@@ -634,7 +634,7 @@
+ unsigned RegA, unsigned RegB,
+ unsigned Dist) {
+ // FIXME: Why does convertToThreeAddress() need an iterator reference?
+- MachineFunction::iterator MFI = MBB;
++ MachineFunction::iterator MFI = MBB->getIterator();
+ MachineInstr *NewMI = TII->convertToThreeAddress(MFI, mi, LV);
+ assert(MBB == MFI && "convertToThreeAddress changed iterator reference");
+ if (!NewMI)
+@@ -1535,7 +1535,7 @@
+ TiedOperandMap TiedOperands;
+ for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
+ MBBI != MBBE; ++MBBI) {
+- MBB = MBBI;
++ MBB = &*MBBI;
+ unsigned Dist = 0;
+ DistanceMap.clear();
+ SrcRegMap.clear();
+--- lib/CodeGen/UnreachableBlockElim.cpp 2014-08-24 16:23:06.000000000 -0700
++++ lib/CodeGen/UnreachableBlockElim.cpp 2015-12-07 08:28:10.169471890 -0800
+@@ -71,8 +71,8 @@
+ // in them.
+ std::vector<BasicBlock*> DeadBlocks;
+ for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
+- if (!Reachable.count(I)) {
+- BasicBlock *BB = I;
++ if (!Reachable.count(&*I)) {
++ BasicBlock *BB = &*I;
+ DeadBlocks.push_back(BB);
+ while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
+ PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
+@@ -131,7 +131,7 @@
+ // in them.
+ std::vector<MachineBasicBlock*> DeadBlocks;
+ for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
+- MachineBasicBlock *BB = I;
++ MachineBasicBlock *BB = &*I;
+
+ // Test for deadness.
+ if (!Reachable.count(BB)) {
+@@ -167,7 +167,7 @@
+
+ // Cleanup PHI nodes.
+ for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
+- MachineBasicBlock *BB = I;
++ MachineBasicBlock *BB = &*I;
+ // Prune unneeded PHI entries.
+ SmallPtrSet<MachineBasicBlock*, 8> preds(BB->pred_begin(),
+ BB->pred_end());
+--- lib/CodeGen/VirtRegMap.cpp 2014-12-10 16:59:06.000000000 -0800
++++ lib/CodeGen/VirtRegMap.cpp 2015-12-07 08:29:40.895828212 -0800
+@@ -312,7 +312,7 @@
+ bool IsExitBB = MBBI->succ_empty();
+ for (MachineBasicBlock::instr_iterator
+ MII = MBBI->instr_begin(), MIE = MBBI->instr_end(); MII != MIE;) {
+- MachineInstr *MI = MII;
++ MachineInstr *MI = &*MII;
+ ++MII;
+
+ // Check if this instruction is a call to a noreturn function. If this
+--- lib/ExecutionEngine/ExecutionEngine.cpp 2014-12-02 16:51:19.000000000 -0800
++++ lib/ExecutionEngine/ExecutionEngine.cpp 2015-12-07 12:04:19.264547988 -0800
+@@ -190,10 +190,10 @@
+ MutexGuard locked(lock);
+
+ for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
+- EEState.RemoveMapping(FI);
++ EEState.RemoveMapping(&*FI);
+ for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
+ GI != GE; ++GI)
+- EEState.RemoveMapping(GI);
++ EEState.RemoveMapping(&*GI);
+ }
+
+ void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
+--- lib/ExecutionEngine/Interpreter/Execution.cpp 2014-04-27 21:05:08.000000000 -0700
++++ lib/ExecutionEngine/Interpreter/Execution.cpp 2015-12-07 12:10:37.392666513 -0800
+@@ -2091,7 +2091,7 @@
+ }
+
+ // Get pointers to first LLVM BB & Instruction in function.
+- StackFrame.CurBB = F->begin();
++ StackFrame.CurBB = &F->front();
+ StackFrame.CurInst = StackFrame.CurBB->begin();
+
+ // Run through the function arguments and initialize their values...
+@@ -2103,7 +2103,7 @@
+ unsigned i = 0;
+ for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
+ AI != E; ++AI, ++i)
+- SetValue(AI, ArgVals[i], StackFrame);
++ SetValue(&*AI, ArgVals[i], StackFrame);
+
+ // Handle varargs arguments...
+ StackFrame.VarArgs.assign(ArgVals.begin()+i, ArgVals.end());
+--- lib/IR/AsmWriter.cpp 2015-01-14 19:59:43.000000000 -0800
++++ lib/IR/AsmWriter.cpp 2015-11-24 08:43:48.354963500 -0800
+@@ -674,14 +674,14 @@
+ for (Module::const_global_iterator I = TheModule->global_begin(),
+ E = TheModule->global_end(); I != E; ++I) {
+ if (!I->hasName())
+- CreateModuleSlot(I);
++ CreateModuleSlot(&(*I));
+ }
+
+ // Add metadata used by named metadata.
+ for (Module::const_named_metadata_iterator
+ I = TheModule->named_metadata_begin(),
+ E = TheModule->named_metadata_end(); I != E; ++I) {
+- const NamedMDNode *NMD = I;
++ const NamedMDNode *NMD = &(*I);
+ for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
+ CreateMetadataSlot(NMD->getOperand(i));
+ }
+@@ -690,7 +690,7 @@
+ I != E; ++I) {
+ if (!I->hasName())
+ // Add all the unnamed functions to the table.
+- CreateModuleSlot(I);
++ CreateModuleSlot(&(*I));
+
+ // Add all the function attributes to the table.
+ // FIXME: Add attributes of other objects?
+@@ -711,7 +711,7 @@
+ for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
+ AE = TheFunction->arg_end(); AI != AE; ++AI)
+ if (!AI->hasName())
+- CreateFunctionSlot(AI);
++ CreateFunctionSlot(&(*AI));
+
+ ST_DEBUG("Inserting Instructions:\n");
+
+@@ -721,12 +721,12 @@
+ for (Function::const_iterator BB = TheFunction->begin(),
+ E = TheFunction->end(); BB != E; ++BB) {
+ if (!BB->hasName())
+- CreateFunctionSlot(BB);
++ CreateFunctionSlot(&(*BB));
+
+ for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
+ ++I) {
+ if (!I->getType()->isVoidTy() && !I->hasName())
+- CreateFunctionSlot(I);
++ CreateFunctionSlot(&(*I));
+
+ // Intrinsics can directly use metadata. We allow direct calls to any
+ // llvm.foo function here, because the target may not be linked into the
+@@ -1607,21 +1607,22 @@
+ if (!M->global_empty()) Out << '\n';
+ for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
+ I != E; ++I) {
+- printGlobal(I); Out << '\n';
++ printGlobal(&(*I));
++ Out << '\n';
+ }
+
+ // Output all aliases.
+ if (!M->alias_empty()) Out << "\n";
+ for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
+ I != E; ++I)
+- printAlias(I);
++ printAlias(&(*I));
+
+ // Output global use-lists.
+ printUseLists(nullptr);
+
+ // Output all of the functions.
+ for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
+- printFunction(I);
++ printFunction(&(*I));
+ assert(UseListOrders.empty() && "All use-lists should have been consumed");
+
+ // Output all attribute groups.
+@@ -1635,7 +1636,7 @@
+
+ for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
+ E = M->named_metadata_end(); I != E; ++I)
+- printNamedMDNode(I);
++ printNamedMDNode(&(*I));
+
+ // Output metadata.
+ if (!Machine.mdn_empty()) {
+@@ -1936,7 +1937,7 @@
+ I != E; ++I) {
+ // Insert commas as we go... the first arg doesn't get a comma
+ if (I != F->arg_begin()) Out << ", ";
+- printArgument(I, Attrs, Idx);
++ printArgument(&(*I), Attrs, Idx);
+ Idx++;
+ }
+ } else {
+@@ -1988,7 +1989,7 @@
+ Out << " {";
+ // Output all of the function's basic blocks.
+ for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
+- printBasicBlock(I);
++ printBasicBlock(&(*I));
+
+ // Output the function's use-lists.
+ printUseLists(F);
+--- lib/IR/AutoUpgrade.cpp 2015-01-14 03:23:27.000000000 -0800
++++ lib/IR/AutoUpgrade.cpp 2015-11-24 09:08:05.216149050 -0800
+@@ -278,7 +278,7 @@
+ Function *F = CI->getCalledFunction();
+ LLVMContext &C = CI->getContext();
+ IRBuilder<> Builder(C);
+- Builder.SetInsertPoint(CI->getParent(), CI);
++ Builder.SetInsertPoint(CI->getParent(), CI->getIterator());
+
+ assert(F && "Intrinsic call is not direct?");
+
+@@ -304,7 +304,7 @@
+ Name == "llvm.x86.avx.movnt.ps.256" ||
+ Name == "llvm.x86.avx.movnt.pd.256") {
+ IRBuilder<> Builder(C);
+- Builder.SetInsertPoint(CI->getParent(), CI);
++ Builder.SetInsertPoint(CI->getParent(), CI->getIterator());
+
+ Module *M = F->getParent();
+ SmallVector<Metadata *, 1> Elts;
+--- lib/IR/BasicBlock.cpp 2014-12-22 05:00:36.000000000 -0800
++++ lib/IR/BasicBlock.cpp 2015-11-24 09:18:34.413275013 -0800
+@@ -60,7 +60,7 @@
+ assert(!Parent && "Already has a parent");
+
+ if (InsertBefore)
+- NewParent->getBasicBlockList().insert(InsertBefore, this);
++ NewParent->getBasicBlockList().insert(InsertBefore->getIterator(), this);
+ else
+ NewParent->getBasicBlockList().push_back(this);
+ }
+@@ -95,26 +95,28 @@
+ }
+
+ void BasicBlock::removeFromParent() {
+- getParent()->getBasicBlockList().remove(this);
++ getParent()->getBasicBlockList().remove(getIterator());
+ }
+
+ void BasicBlock::eraseFromParent() {
+- getParent()->getBasicBlockList().erase(this);
++ getParent()->getBasicBlockList().erase(getIterator());
+ }
+
+ /// moveBefore - Unlink this basic block from its current function and
+ /// insert it into the function that MovePos lives in, right before MovePos.
+ void BasicBlock::moveBefore(BasicBlock *MovePos) {
+- MovePos->getParent()->getBasicBlockList().splice(MovePos,
+- getParent()->getBasicBlockList(), this);
++ MovePos->getParent()->getBasicBlockList().splice(MovePos->getIterator(),
++ getParent()->getBasicBlockList(), getIterator());
+ }
+
+ /// moveAfter - Unlink this basic block from its current function and
+ /// insert it into the function that MovePos lives in, right after MovePos.
+ void BasicBlock::moveAfter(BasicBlock *MovePos) {
+- Function::iterator I = MovePos;
+- MovePos->getParent()->getBasicBlockList().splice(++I,
+- getParent()->getBasicBlockList(), this);
++ Function::iterator I = MovePos->getIterator();
++ Function::iterator II = ++I;
++ MovePos->getParent()->getBasicBlockList().splice(II,
++ getParent()->getBasicBlockList(),
++ getIterator());
+ }
+
+
+@@ -200,7 +202,7 @@
+ }
+
+ BasicBlock::iterator BasicBlock::getFirstInsertionPt() {
+- iterator InsertPt = getFirstNonPHI();
++ iterator InsertPt = getFirstNonPHI()->getIterator();
+ if (isa<LandingPadInst>(InsertPt)) ++InsertPt;
+ return InsertPt;
+ }
+--- lib/IR/Core.cpp 2015-01-29 09:33:19.000000000 -0800
++++ lib/IR/Core.cpp 2015-11-24 20:09:32.108977930 -0800
+@@ -1517,7 +1517,8 @@
+ Module::global_iterator I = Mod->global_begin();
+ if (I == Mod->global_end())
+ return nullptr;
+- return wrap(I);
++
++ return wrap(&(*I));
+ }
+
+ LLVMValueRef LLVMGetLastGlobal(LLVMModuleRef M) {
+@@ -1525,23 +1526,28 @@
+ Module::global_iterator I = Mod->global_end();
+ if (I == Mod->global_begin())
+ return nullptr;
+- return wrap(--I);
++
++ --I;
++ return wrap(&(*I));
+ }
+
+ LLVMValueRef LLVMGetNextGlobal(LLVMValueRef GlobalVar) {
+ GlobalVariable *GV = unwrap<GlobalVariable>(GlobalVar);
+- Module::global_iterator I = GV;
++ Module::global_iterator I(GV);
+ if (++I == GV->getParent()->global_end())
+ return nullptr;
+- return wrap(I);
++
++ return wrap(&(*I));
+ }
+
+ LLVMValueRef LLVMGetPreviousGlobal(LLVMValueRef GlobalVar) {
+ GlobalVariable *GV = unwrap<GlobalVariable>(GlobalVar);
+- Module::global_iterator I = GV;
++ Module::global_iterator I(GV);
+ if (I == GV->getParent()->global_begin())
+ return nullptr;
+- return wrap(--I);
++
++ --I;
++ return wrap(&(*I));
+ }
+
+ void LLVMDeleteGlobal(LLVMValueRef GlobalVar) {
+@@ -1550,8 +1556,9 @@
+
+ LLVMValueRef LLVMGetInitializer(LLVMValueRef GlobalVar) {
+ GlobalVariable* GV = unwrap<GlobalVariable>(GlobalVar);
+- if ( !GV->hasInitializer() )
++ if (!GV->hasInitializer())
+ return nullptr;
++
+ return wrap(GV->getInitializer());
+ }
+
+@@ -1650,7 +1657,8 @@
+ Module::iterator I = Mod->begin();
+ if (I == Mod->end())
+ return nullptr;
+- return wrap(I);
++
++ return wrap(&(*I));
+ }
+
+ LLVMValueRef LLVMGetLastFunction(LLVMModuleRef M) {
+@@ -1658,23 +1666,28 @@
+ Module::iterator I = Mod->end();
+ if (I == Mod->begin())
+ return nullptr;
+- return wrap(--I);
++
++ --I;
++ return wrap(&(*I));
+ }
+
+ LLVMValueRef LLVMGetNextFunction(LLVMValueRef Fn) {
+ Function *Func = unwrap<Function>(Fn);
+- Module::iterator I = Func;
++ Module::iterator I(Func);
+ if (++I == Func->getParent()->end())
+ return nullptr;
+- return wrap(I);
++
++ return wrap(&(*I));
+ }
+
+ LLVMValueRef LLVMGetPreviousFunction(LLVMValueRef Fn) {
+ Function *Func = unwrap<Function>(Fn);
+- Module::iterator I = Func;
++ Module::iterator I(Func);
+ if (I == Func->getParent()->begin())
+ return nullptr;
+- return wrap(--I);
++
++ --I;
++ return wrap(&(*I));
+ }
+
+ void LLVMDeleteFunction(LLVMValueRef Fn) {
+@@ -1684,6 +1697,7 @@
+ unsigned LLVMGetIntrinsicID(LLVMValueRef Fn) {
+ if (Function *F = dyn_cast<Function>(unwrap(Fn)))
+ return F->getIntrinsicID();
++
+ return 0;
+ }
+
+@@ -1698,7 +1712,7 @@
+
+ const char *LLVMGetGC(LLVMValueRef Fn) {
+ Function *F = unwrap<Function>(Fn);
+- return F->hasGC()? F->getGC() : nullptr;
++ return F->hasGC() ? F->getGC() : nullptr;
+ }
+
+ void LLVMSetGC(LLVMValueRef Fn, const char *GC) {
+@@ -1761,14 +1775,15 @@
+ Function *Fn = unwrap<Function>(FnRef);
+ for (Function::arg_iterator I = Fn->arg_begin(),
+ E = Fn->arg_end(); I != E; I++)
+- *ParamRefs++ = wrap(I);
++ *ParamRefs++ = wrap(&(*I));
+ }
+
+ LLVMValueRef LLVMGetParam(LLVMValueRef FnRef, unsigned index) {
+ Function::arg_iterator AI = unwrap<Function>(FnRef)->arg_begin();
+ while (index --> 0)
+ AI++;
+- return wrap(AI);
++
++ return wrap(&(*AI));
+ }
+
+ LLVMValueRef LLVMGetParamParent(LLVMValueRef V) {
+@@ -1780,7 +1795,8 @@
+ Function::arg_iterator I = Func->arg_begin();
+ if (I == Func->arg_end())
+ return nullptr;
+- return wrap(I);
++
++ return wrap(&(*I));
+ }
+
+ LLVMValueRef LLVMGetLastParam(LLVMValueRef Fn) {
+@@ -1788,23 +1804,28 @@
+ Function::arg_iterator I = Func->arg_end();
+ if (I == Func->arg_begin())
+ return nullptr;
+- return wrap(--I);
++
++ --I;
++ return wrap(&(*I));
+ }
+
+ LLVMValueRef LLVMGetNextParam(LLVMValueRef Arg) {
+ Argument *A = unwrap<Argument>(Arg);
+- Function::arg_iterator I = A;
++ Function::arg_iterator I(A);
+ if (++I == A->getParent()->arg_end())
+ return nullptr;
+- return wrap(I);
++
++ return wrap(&(*I));
+ }
+
+ LLVMValueRef LLVMGetPreviousParam(LLVMValueRef Arg) {
+ Argument *A = unwrap<Argument>(Arg);
+- Function::arg_iterator I = A;
++ Function::arg_iterator I(A);
+ if (I == A->getParent()->arg_begin())
+ return nullptr;
+- return wrap(--I);
++
++ --I;
++ return wrap(&(*I));
+ }
+
+ void LLVMAddAttribute(LLVMValueRef Arg, LLVMAttribute PA) {
+@@ -1862,7 +1883,7 @@
+ void LLVMGetBasicBlocks(LLVMValueRef FnRef, LLVMBasicBlockRef *BasicBlocksRefs){
+ Function *Fn = unwrap<Function>(FnRef);
+ for (Function::iterator I = Fn->begin(), E = Fn->end(); I != E; I++)
+- *BasicBlocksRefs++ = wrap(I);
++ *BasicBlocksRefs++ = wrap(&(*I));
+ }
+
+ LLVMBasicBlockRef LLVMGetEntryBasicBlock(LLVMValueRef Fn) {
+@@ -1874,7 +1895,8 @@
+ Function::iterator I = Func->begin();
+ if (I == Func->end())
+ return nullptr;
+- return wrap(I);
++
++ return wrap(&(*I));
+ }
+
+ LLVMBasicBlockRef LLVMGetLastBasicBlock(LLVMValueRef Fn) {
+@@ -1882,23 +1904,28 @@
+ Function::iterator I = Func->end();
+ if (I == Func->begin())
+ return nullptr;
+- return wrap(--I);
++
++ --I;
++ return wrap(&(*I));
+ }
+
+ LLVMBasicBlockRef LLVMGetNextBasicBlock(LLVMBasicBlockRef BB) {
+ BasicBlock *Block = unwrap(BB);
+- Function::iterator I = Block;
++ Function::iterator I(Block);
+ if (++I == Block->getParent()->end())
+ return nullptr;
+- return wrap(I);
++
++ return wrap(&(*I));
+ }
+
+ LLVMBasicBlockRef LLVMGetPreviousBasicBlock(LLVMBasicBlockRef BB) {
+ BasicBlock *Block = unwrap(BB);
+- Function::iterator I = Block;
++ Function::iterator I(Block);
+ if (I == Block->getParent()->begin())
+ return nullptr;
+- return wrap(--I);
++
++ --I;
++ return wrap(&(*I));
+ }
+
+ LLVMBasicBlockRef LLVMAppendBasicBlockInContext(LLVMContextRef C,
+@@ -1950,7 +1977,8 @@
+ BasicBlock::iterator I = Block->begin();
+ if (I == Block->end())
+ return nullptr;
+- return wrap(I);
++
++ return wrap(&(*I));
+ }
+
+ LLVMValueRef LLVMGetLastInstruction(LLVMBasicBlockRef BB) {
+@@ -1958,23 +1986,28 @@
+ BasicBlock::iterator I = Block->end();
+ if (I == Block->begin())
+ return nullptr;
+- return wrap(--I);
++
++ --I;
++ return wrap(&(*I));
+ }
+
+ LLVMValueRef LLVMGetNextInstruction(LLVMValueRef Inst) {
+ Instruction *Instr = unwrap<Instruction>(Inst);
+- BasicBlock::iterator I = Instr;
++ BasicBlock::iterator I(Instr);
+ if (++I == Instr->getParent()->end())
+ return nullptr;
+- return wrap(I);
++
++ return wrap(&(*I));
+ }
+
+ LLVMValueRef LLVMGetPreviousInstruction(LLVMValueRef Inst) {
+ Instruction *Instr = unwrap<Instruction>(Inst);
+- BasicBlock::iterator I = Instr;
++ BasicBlock::iterator I(Instr);
+ if (I == Instr->getParent()->begin())
+ return nullptr;
+- return wrap(--I);
++
++ --I;
++ return wrap(&(*I));
+ }
+
+ void LLVMInstructionEraseFromParent(LLVMValueRef Inst) {
+@@ -2142,12 +2175,12 @@
+ LLVMValueRef Instr) {
+ BasicBlock *BB = unwrap(Block);
+ Instruction *I = Instr? unwrap<Instruction>(Instr) : (Instruction*) BB->end();
+- unwrap(Builder)->SetInsertPoint(BB, I);
++ unwrap(Builder)->SetInsertPoint(BB, I->getIterator());
+ }
+
+ void LLVMPositionBuilderBefore(LLVMBuilderRef Builder, LLVMValueRef Instr) {
+ Instruction *I = unwrap<Instruction>(Instr);
+- unwrap(Builder)->SetInsertPoint(I->getParent(), I);
++ unwrap(Builder)->SetInsertPoint(I->getParent(), I->getIterator());
+ }
+
+ void LLVMPositionBuilderAtEnd(LLVMBuilderRef Builder, LLVMBasicBlockRef Block) {
+--- lib/IR/DebugInfo.cpp 2015-02-12 15:46:59.000000000 -0800
++++ lib/IR/DebugInfo.cpp 2015-11-24 20:11:47.916206795 -0800
+@@ -1485,7 +1485,7 @@
+
+ for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
+ NME = M.named_metadata_end(); NMI != NME;) {
+- NamedMDNode *NMD = NMI;
++ NamedMDNode *NMD = &(*NMI);
+ ++NMI;
+ if (NMD->getName().startswith("llvm.dbg.")) {
+ NMD->eraseFromParent();
+--- lib/IR/Function.cpp 2014-12-24 23:49:20.000000000 -0800
++++ lib/IR/Function.cpp 2015-11-27 09:29:07.971979862 -0800
+@@ -228,11 +228,11 @@
+ }
+
+ void Function::removeFromParent() {
+- getParent()->getFunctionList().remove(this);
++ getParent()->getFunctionList().remove(getIterator());
+ }
+
+ void Function::eraseFromParent() {
+- getParent()->getFunctionList().erase(this);
++ getParent()->getFunctionList().erase(getIterator());
+ }
+
+ //===----------------------------------------------------------------------===//
+--- lib/IR/Globals.cpp 2014-12-22 05:00:36.000000000 -0800
++++ lib/IR/Globals.cpp 2015-11-27 06:06:12.109691445 -0800
+@@ -178,7 +178,7 @@
+ }
+
+ if (Before)
+- Before->getParent()->getGlobalList().insert(Before, this);
++ Before->getParent()->getGlobalList().insert(Before->getIterator(), this);
+ else
+ M.getGlobalList().push_back(this);
+ }
+@@ -188,11 +188,11 @@
+ }
+
+ void GlobalVariable::removeFromParent() {
+- getParent()->getGlobalList().remove(this);
++ getParent()->getGlobalList().remove(getIterator());
+ }
+
+ void GlobalVariable::eraseFromParent() {
+- getParent()->getGlobalList().erase(this);
++ getParent()->getGlobalList().erase(getIterator());
+ }
+
+ void GlobalVariable::replaceUsesOfWithOnConstant(Value *From, Value *To,
+@@ -290,11 +290,11 @@
+ }
+
+ void GlobalAlias::removeFromParent() {
+- getParent()->getAliasList().remove(this);
++ getParent()->getAliasList().remove(getIterator());
+ }
+
+ void GlobalAlias::eraseFromParent() {
+- getParent()->getAliasList().erase(this);
++ getParent()->getAliasList().erase(getIterator());
+ }
+
+ void GlobalAlias::setAliasee(Constant *Aliasee) {
+--- lib/IR/Instruction.cpp 2014-12-22 05:00:36.000000000 -0800
++++ lib/IR/Instruction.cpp 2015-11-27 07:26:46.480147123 -0800
+@@ -26,9 +26,9 @@
+
+ // If requested, insert this instruction into a basic block...
+ if (InsertBefore) {
+- assert(InsertBefore->getParent() &&
+- "Instruction to insert before is not in a basic block!");
+- InsertBefore->getParent()->getInstList().insert(InsertBefore, this);
++ BasicBlock *BB = InsertBefore->getParent();
++ assert(BB && "Instruction to insert before is not in a basic block!");
++ BB->getInstList().insert(InsertBefore->getIterator(), this);
+ }
+ }
+
+@@ -59,31 +59,33 @@
+ }
+
+ void Instruction::removeFromParent() {
+- getParent()->getInstList().remove(this);
++ getParent()->getInstList().remove(getIterator());
+ }
+
+ void Instruction::eraseFromParent() {
+- getParent()->getInstList().erase(this);
++ getParent()->getInstList().erase(getIterator());
+ }
+
+ /// insertBefore - Insert an unlinked instructions into a basic block
+ /// immediately before the specified instruction.
+ void Instruction::insertBefore(Instruction *InsertPos) {
+- InsertPos->getParent()->getInstList().insert(InsertPos, this);
++ InsertPos->getParent()->getInstList().insert(InsertPos->getIterator(), this);
+ }
+
+ /// insertAfter - Insert an unlinked instructions into a basic block
+ /// immediately after the specified instruction.
+ void Instruction::insertAfter(Instruction *InsertPos) {
+- InsertPos->getParent()->getInstList().insertAfter(InsertPos, this);
++ InsertPos->getParent()->getInstList().insertAfter(InsertPos->getIterator(),
++ this);
+ }
+
+ /// moveBefore - Unlink this instruction from its current basic block and
+ /// insert it into the basic block that MovePos lives in, right before
+ /// MovePos.
+ void Instruction::moveBefore(Instruction *MovePos) {
+- MovePos->getParent()->getInstList().splice(MovePos,getParent()->getInstList(),
+- this);
++ MovePos->getParent()->getInstList().splice(MovePos->getIterator(),
++ getParent()->getInstList(),
++ getIterator());
+ }
+
+ /// Set or clear the unsafe-algebra flag on this instruction, which must be an
+--- lib/IR/Module.cpp 2014-12-22 05:00:36.000000000 -0800
++++ lib/IR/Module.cpp 2015-11-27 09:30:00.064132788 -0800
+@@ -274,7 +274,7 @@
+ /// delete it.
+ void Module::eraseNamedMetadata(NamedMDNode *NMD) {
+ static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
+- NamedMDList.erase(NMD);
++ NamedMDList.erase(NMD->getIterator());
+ }
+
+ bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
+--- lib/IR/SymbolTableListTraitsImpl.h 2014-08-13 09:26:38.000000000 -0700
++++ lib/IR/SymbolTableListTraitsImpl.h 2015-11-24 12:37:36.693556920 -0800
+@@ -57,7 +57,7 @@
+ for (typename iplist<ValueSubClass>::iterator I = ItemList.begin();
+ I != ItemList.end(); ++I)
+ if (I->hasName())
+- NewST->reinsertValue(I);
++ NewST->reinsertValue(&(*I));
+ }
+
+ }
+--- lib/IR/TypeFinder.cpp 2014-12-09 10:38:53.000000000 -0800
++++ lib/IR/TypeFinder.cpp 2015-11-27 07:40:03.669762910 -0800
+@@ -53,7 +53,7 @@
+ // First incorporate the arguments.
+ for (Function::const_arg_iterator AI = FI->arg_begin(),
+ AE = FI->arg_end(); AI != AE; ++AI)
+- incorporateValue(AI);
++ incorporateValue(&(*AI));
+
+ for (Function::const_iterator BB = FI->begin(), E = FI->end();
+ BB != E;++BB)
+@@ -82,7 +82,7 @@
+
+ for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
+ E = M.named_metadata_end(); I != E; ++I) {
+- const NamedMDNode *NMD = I;
++ const NamedMDNode *NMD = &(*I);
+ for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
+ incorporateMDNode(NMD->getOperand(i));
+ }
+--- lib/IR/Verifier.cpp 2015-01-12 19:46:47.000000000 -0800
++++ lib/IR/Verifier.cpp 2015-11-27 09:27:19.724275928 -0800
+@@ -81,7 +81,8 @@
+ static cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(false));
+
+ namespace {
+-struct VerifierSupport {
++class VerifierSupport {
++public:
+ raw_ostream &OS;
+ const Module *M;
+
+@@ -89,11 +90,15 @@
+ bool Broken;
+
+ explicit VerifierSupport(raw_ostream &OS)
+- : OS(OS), M(nullptr), Broken(false) {}
++ : OS(OS), M(nullptr), Broken(false) { }
++
++ ~VerifierSupport() { }
+
+- void WriteValue(const Value *V) {
++private:
++ void Write(const Value *V) {
+ if (!V)
+ return;
++
+ if (isa<Instruction>(V)) {
+ OS << *V << '\n';
+ } else {
+@@ -102,81 +107,69 @@
+ }
+ }
+
+- void WriteMetadata(const Metadata *MD) {
++ void Write(const Metadata *MD) {
+ if (!MD)
+ return;
++
+ MD->printAsOperand(OS, true, M);
+ OS << '\n';
+ }
+
+- void WriteType(Type *T) {
++ void Write(Type *T) {
+ if (!T)
+ return;
++
+ OS << ' ' << *T;
+ }
+
+- void WriteComdat(const Comdat *C) {
++ void Write(const Comdat *C) {
+ if (!C)
+ return;
++
+ OS << *C;
+ }
+
+- // CheckFailed - A check failed, so print out the condition and the message
+- // that failed. This provides a nice place to put a breakpoint if you want
+- // to see why something is not correct.
+- void CheckFailed(const Twine &Message, const Value *V1 = nullptr,
+- const Value *V2 = nullptr, const Value *V3 = nullptr,
+- const Value *V4 = nullptr) {
+- OS << Message.str() << "\n";
+- WriteValue(V1);
+- WriteValue(V2);
+- WriteValue(V3);
+- WriteValue(V4);
+- Broken = true;
+- }
++ void Write(const NamedMDNode *NMD) {
++ if (!NMD)
++ return;
+
+- void CheckFailed(const Twine &Message, const Metadata *V1, const Metadata *V2,
+- const Metadata *V3 = nullptr, const Metadata *V4 = nullptr) {
+- OS << Message.str() << "\n";
+- WriteMetadata(V1);
+- WriteMetadata(V2);
+- WriteMetadata(V3);
+- WriteMetadata(V4);
+- Broken = true;
++ NMD->print(OS);
++ OS << "\n";
+ }
+
+- void CheckFailed(const Twine &Message, const Metadata *V1,
+- const Value *V2 = nullptr) {
+- OS << Message.str() << "\n";
+- WriteMetadata(V1);
+- WriteValue(V2);
+- Broken = true;
++ template<class T>
++ void Write(const MDTupleTypedArrayWrapper<T> &MD) {
++ Write(MD.get());
+ }
+
+- void CheckFailed(const Twine &Message, const Value *V1, Type *T2,
+- const Value *V3 = nullptr) {
+- OS << Message.str() << "\n";
+- WriteValue(V1);
+- WriteType(T2);
+- WriteValue(V3);
+- Broken = true;
++ template<class NodeTy> void Write(const ilist_iterator<NodeTy> &I) {
++ Write(&(*I));
+ }
+
+- void CheckFailed(const Twine &Message, Type *T1, Type *T2 = nullptr,
+- Type *T3 = nullptr) {
+- OS << Message.str() << "\n";
+- WriteType(T1);
+- WriteType(T2);
+- WriteType(T3);
++ template <typename T1, typename... Ts>
++ void WriteTs(const T1 &V1, const Ts &... Vs) {
++ Write(V1);
++ WriteTs(Vs...);
++ }
++
++ template <typename... Ts> void WriteTs() {}
++
++public:
++ // CheckFailed - A check failed, so print out the condition and the message
++ // that failed. This provides a nice place to put a breakpoint if you want
++ // to see why something is not correct.
++ void CheckFailed(const Twine &Message) {
++ OS << Message << '\n';
+ Broken = true;
+ }
+
+- void CheckFailed(const Twine &Message, const Comdat *C) {
+- OS << Message.str() << "\n";
+- WriteComdat(C);
+- Broken = true;
++ template <typename T1, typename... Ts>
++ void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
++ CheckFailed(Message);
++ WriteTs(V1, Vs...);
+ }
+ };
++
+ class Verifier : public InstVisitor<Verifier>, VerifierSupport {
+ friend class InstVisitor<Verifier>;
+
+@@ -204,8 +197,10 @@
+
+ public:
+ explicit Verifier(raw_ostream &OS = dbgs())
+- : VerifierSupport(OS), Context(nullptr), PersonalityFn(nullptr),
+- SawFrameAllocate(false) {}
++ : InstVisitor<Verifier>(),
++ VerifierSupport(OS), Context(nullptr), DT(),
++ InstsInThisBlock(), MDNodes(),
++ PersonalityFn(nullptr), SawFrameAllocate(false) { }
+
+ bool verify(const Function &F) {
+ M = F.getParent();
+@@ -538,8 +533,6 @@
+ void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
+ const GlobalAlias &GA, const Constant &C) {
+ if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
+- Assert1(!GV->isDeclaration(), "Alias must point to a definition", &GA);
+-
+ if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
+ Assert1(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
+
+--- lib/Linker/LinkModules.cpp 2015-02-24 18:00:21.000000000 -0800
++++ lib/Linker/LinkModules.cpp 2015-12-07 12:26:23.891323205 -0800
+@@ -1194,7 +1194,7 @@
+ DI->setName(Arg.getName()); // Copy the name over.
+
+ // Add a mapping to our mapping.
+- ValueMap[&Arg] = DI;
++ ValueMap[&Arg] = &*DI;
+ ++DI;
+ }
+
+@@ -1518,7 +1518,7 @@
+ // initializers (which could refer to functions not yet mapped over).
+ for (Module::global_iterator I = SrcM->global_begin(),
+ E = SrcM->global_end(); I != E; ++I)
+- if (linkGlobalValueProto(I))
++ if (linkGlobalValueProto(&*I))
+ return true;
+
+ // Link the functions together between the two modules, without doing function
+@@ -1527,13 +1527,13 @@
+ // all of the global values that may be referenced are available in our
+ // ValueMap.
+ for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
+- if (linkGlobalValueProto(I))
++ if (linkGlobalValueProto(&*I))
+ return true;
+
+ // If there were any aliases, link them now.
+ for (Module::alias_iterator I = SrcM->alias_begin(),
+ E = SrcM->alias_end(); I != E; ++I)
+- if (linkGlobalValueProto(I))
++ if (linkGlobalValueProto(&*I))
+ return true;
+
+ for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
+--- lib/MC/MCAssembler.cpp 2015-01-16 16:38:54.000000000 -0800
++++ lib/MC/MCAssembler.cpp 2015-12-07 12:37:47.486088108 -0800
+@@ -315,11 +315,13 @@
+ if (ExactMatch)
+ ++MI;
+ }
++
+ iterator IP;
+ if (MI == SubsectionFragmentMap.end())
+ IP = end();
+ else
+- IP = MI->second;
++ IP = MI->second->getIterator();
++
+ if (!ExactMatch && Subsection != 0) {
+ // The GNU as documentation claims that subsections have an alignment of 4,
+ // although this appears not to be the case.
+@@ -892,7 +894,7 @@
+ // Create dummy fragments to eliminate any empty sections, this simplifies
+ // layout.
+ if (it->getFragmentList().empty())
+- new MCDataFragment(it);
++ new MCDataFragment(&*it);
+
+ it->setOrdinal(SectionIndex++);
+ }
+@@ -1091,7 +1093,7 @@
+ break;
+ }
+ if (RelaxedFrag && !FirstRelaxedFragment)
+- FirstRelaxedFragment = I;
++ FirstRelaxedFragment = &*I;
+ }
+ if (FirstRelaxedFragment) {
+ Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
+--- lib/MC/MCMachOStreamer.cpp 2014-09-17 02:25:36.000000000 -0700
++++ lib/MC/MCMachOStreamer.cpp 2015-12-07 12:41:51.654959723 -0800
+@@ -444,7 +444,7 @@
+ MCSymbolData *CurrentAtom = nullptr;
+ for (MCSectionData::iterator it2 = it->begin(),
+ ie2 = it->end(); it2 != ie2; ++it2) {
+- if (MCSymbolData *SD = DefiningSymbolMap.lookup(it2))
++ if (MCSymbolData *SD = DefiningSymbolMap.lookup(&*it2))
+ CurrentAtom = SD;
+ it2->setAtom(CurrentAtom);
+ }
+--- lib/MC/MCObjectStreamer.cpp 2014-12-12 13:48:03.000000000 -0800
++++ lib/MC/MCObjectStreamer.cpp 2015-12-07 12:52:20.758780735 -0800
+@@ -83,7 +83,7 @@
+ assert(getCurrentSectionData() && "No current section!");
+
+ if (CurInsertionPoint != getCurrentSectionData()->getFragmentList().begin())
+- return std::prev(CurInsertionPoint);
++ return &*std::prev(CurInsertionPoint);
+
+ return nullptr;
+ }
+--- lib/MC/MachObjectWriter.cpp 2015-01-16 16:38:54.000000000 -0800
++++ lib/MC/MachObjectWriter.cpp 2015-12-07 13:28:29.179917460 -0800
+@@ -839,9 +839,9 @@
+ uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
+ for (MCAssembler::const_iterator it = Asm.begin(),
+ ie = Asm.end(); it != ie; ++it) {
+- std::vector<MachO::any_relocation_info> &Relocs = Relocations[it];
++ std::vector<MachO::any_relocation_info> &Relocs = Relocations[&*it];
+ unsigned NumRelocs = Relocs.size();
+- uint64_t SectionStart = SectionDataStart + getSectionAddress(it);
++ uint64_t SectionStart = SectionDataStart + getSectionAddress(&*it);
+ WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
+ RelocTableEnd += NumRelocs * sizeof(MachO::any_relocation_info);
+ }
+@@ -918,9 +918,9 @@
+ // Write the actual section data.
+ for (MCAssembler::const_iterator it = Asm.begin(),
+ ie = Asm.end(); it != ie; ++it) {
+- Asm.writeSectionData(it, Layout);
++ Asm.writeSectionData(&*it, Layout);
+
+- uint64_t Pad = getPaddingSize(it, Layout);
++ uint64_t Pad = getPaddingSize(&*it, Layout);
+ for (unsigned int i = 0; i < Pad; ++i)
+ Write8(0);
+ }
+@@ -933,7 +933,7 @@
+ ie = Asm.end(); it != ie; ++it) {
+ // Write the section relocation entries, in reverse order to match 'as'
+ // (approximately, the exact algorithm is more complicated than this).
+- std::vector<MachO::any_relocation_info> &Relocs = Relocations[it];
++ std::vector<MachO::any_relocation_info> &Relocs = Relocations[&*it];
+ for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
+ Write32(Relocs[e - i - 1].r_word0);
+ Write32(Relocs[e - i - 1].r_word1);
+--- lib/MC/WinCOFFObjectWriter.cpp 2015-02-09 19:52:36.000000000 -0800
++++ lib/MC/WinCOFFObjectWriter.cpp 2015-12-07 14:55:13.070245970 -0800
+@@ -1015,7 +1015,7 @@
+ assert(OS.tell() == (*i)->Header.PointerToRawData &&
+ "Section::PointerToRawData is insane!");
+
+- Asm.writeSectionData(j, Layout);
++ Asm.writeSectionData(&*j, Layout);
+ }
+
+ if ((*i)->Relocations.size() > 0) {
+--- lib/Support/YAMLParser.cpp 2014-08-30 09:48:02.000000000 -0700
++++ lib/Support/YAMLParser.cpp 2015-11-27 18:09:35.106421600 -0800
+@@ -393,9 +393,10 @@
+ bool isBlankOrBreak(StringRef::iterator Position);
+
+ /// @brief If IsSimpleKeyAllowed, create and push_back a new SimpleKey.
+- void saveSimpleKeyCandidate( TokenQueueT::iterator Tok
+- , unsigned AtColumn
+- , bool IsRequired);
++ /// Please cut the comma placement bullshit. Thank you.
++ void saveSimpleKeyCandidate(TokenQueueT::iterator Tok,
++ unsigned AtColumn,
++ bool IsRequired);
+
+ /// @brief Remove simple keys that can no longer be valid simple keys.
+ ///
+@@ -742,7 +743,7 @@
+
+ removeStaleSimpleKeyCandidates();
+ SimpleKey SK;
+- SK.Tok = TokenQueue.front();
++ SK.Tok = TokenQueue.begin();
+ if (std::find(SimpleKeys.begin(), SimpleKeys.end(), SK)
+ == SimpleKeys.end())
+ break;
+@@ -896,9 +897,9 @@
+ return false;
+ }
+
+-void Scanner::saveSimpleKeyCandidate( TokenQueueT::iterator Tok
+- , unsigned AtColumn
+- , bool IsRequired) {
++void Scanner::saveSimpleKeyCandidate(TokenQueueT::iterator Tok,
++ unsigned AtColumn,
++ bool IsRequired) {
+ if (IsSimpleKeyAllowed) {
+ SimpleKey SK;
+ SK.Tok = Tok;
+@@ -1078,7 +1079,7 @@
+ TokenQueue.push_back(T);
+
+ // [ and { may begin a simple key.
+- saveSimpleKeyCandidate(TokenQueue.back(), Column - 1, false);
++ saveSimpleKeyCandidate(--TokenQueue.end(), Column - 1, false);
+
+ // And may also be followed by a simple key.
+ IsSimpleKeyAllowed = true;
+@@ -1241,7 +1242,7 @@
+ T.Range = StringRef(Start, Current - Start);
+ TokenQueue.push_back(T);
+
+- saveSimpleKeyCandidate(TokenQueue.back(), ColStart, false);
++ saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
+
+ IsSimpleKeyAllowed = false;
+
+@@ -1319,7 +1320,7 @@
+ TokenQueue.push_back(T);
+
+ // Plain scalars can be simple keys.
+- saveSimpleKeyCandidate(TokenQueue.back(), ColStart, false);
++ saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
+
+ IsSimpleKeyAllowed = false;
+
+@@ -1354,7 +1355,7 @@
+ TokenQueue.push_back(T);
+
+ // Alias and anchors can be simple keys.
+- saveSimpleKeyCandidate(TokenQueue.back(), ColStart, false);
++ saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
+
+ IsSimpleKeyAllowed = false;
+
+@@ -1418,7 +1419,7 @@
+ TokenQueue.push_back(T);
+
+ // Tags can be simple keys.
+- saveSimpleKeyCandidate(TokenQueue.back(), ColStart, false);
++ saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
+
+ IsSimpleKeyAllowed = false;
+
+--- lib/Target/Sparc/SparcAsmPrinter.cpp 2014-08-04 14:25:23.000000000 -0700
++++ lib/Target/Sparc/SparcAsmPrinter.cpp 2015-12-07 11:54:08.441400090 -0800
+@@ -267,11 +267,11 @@
+ LowerGETPCXAndEmitMCInsts(MI, getSubtargetInfo());
+ return;
+ }
+- MachineBasicBlock::const_instr_iterator I = MI;
++ MachineBasicBlock::const_instr_iterator I = MI->getIterator();
+ MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
+ do {
+ MCInst TmpInst;
+- LowerSparcMachineInstrToMCInst(I, TmpInst, *this);
++ LowerSparcMachineInstrToMCInst(&*I, TmpInst, *this);
+ EmitToStreamer(OutStreamer, TmpInst);
+ } while ((++I != E) && I->isInsideBundle()); // Delay slot check.
+ }
+--- lib/Target/Sparc/SparcISelLowering.cpp 2015-01-07 16:51:32.000000000 -0800
++++ lib/Target/Sparc/SparcISelLowering.cpp 2015-12-07 11:59:14.697760005 -0800
+@@ -2916,8 +2916,7 @@
+ // to set, the condition code register to branch on, the true/false values to
+ // select between, and a branch opcode to use.
+ const BasicBlock *LLVM_BB = BB->getBasicBlock();
+- MachineFunction::iterator It = BB;
+- ++It;
++ MachineFunction::iterator It = ++BB->getIterator();
+
+ // thisMBB:
+ // ...
+@@ -3003,7 +3002,7 @@
+ .addReg(AddrReg).addImm(0);
+
+ // Split the basic block MBB before MI and insert the loop block in the hole.
+- MachineFunction::iterator MFI = MBB;
++ MachineFunction::iterator MFI = MBB->getIterator();
+ const BasicBlock *LLVM_BB = MBB->getBasicBlock();
+ MachineFunction *MF = MBB->getParent();
+ MachineBasicBlock *LoopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
+--- lib/Target/Sparc/SparcTargetObjectFile.cpp 2014-04-24 22:30:21.000000000 -0700
++++ lib/Target/Sparc/SparcTargetObjectFile.cpp 2015-12-15 12:44:57.569902985 -0800
+@@ -15,6 +15,17 @@
+
+ using namespace llvm;
+
++void SparcELFTargetObjectFile::Initialize(MCContext &CTX,
++ const TargetMachine &TM) {
++ TargetLoweringObjectFile::Initialize(CTX, TM);
++ std::string OS = TM.getTargetTriple().str();
++
++ if (OS.find("solaris") != std::string::npos)
++ InitializeELF(true);
++ else
++ InitializeELF(TM.Options.UseInitArray);
++}
++
+ const MCExpr *SparcELFTargetObjectFile::getTTypeGlobalReference(
+ const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
+ const TargetMachine &TM, MachineModuleInfo *MMI,
+--- lib/Target/Sparc/SparcTargetObjectFile.h 2014-08-13 09:26:38.000000000 -0700
++++ lib/Target/Sparc/SparcTargetObjectFile.h 2015-12-15 12:37:54.653197100 -0800
+@@ -19,11 +19,11 @@
+
+ class SparcELFTargetObjectFile : public TargetLoweringObjectFileELF {
+ public:
+- SparcELFTargetObjectFile() :
+- TargetLoweringObjectFileELF()
+- {}
++ SparcELFTargetObjectFile() : TargetLoweringObjectFileELF() { }
+
+- const MCExpr *
++ virtual void Initialize(MCContext &CTX, const TargetMachine &TM) override;
++
++ const MCExpr*
+ getTTypeGlobalReference(const GlobalValue *GV, unsigned Encoding,
+ Mangler &Mang, const TargetMachine &TM,
+ MachineModuleInfo *MMI,
+--- lib/Target/X86/X86FastISel.cpp 2015-01-05 23:35:50.000000000 -0800
++++ lib/Target/X86/X86FastISel.cpp 2016-01-23 08:58:44.000000000 -0800
+@@ -275,8 +275,8 @@
+ return false;
+
+ // Make sure nothing is in the way
+- BasicBlock::const_iterator Start = I;
+- BasicBlock::const_iterator End = II;
++ BasicBlock::const_iterator Start(I);
++ BasicBlock::const_iterator End(II);
+ for (auto Itr = std::prev(Start); Itr != End; --Itr) {
+ // We only expect extractvalue instructions between the intrinsic and the
+ // instruction to be selected.
+--- lib/Target/X86/X86FixupLEAs.cpp 2015-01-05 02:15:49.000000000 -0800
++++ lib/Target/X86/X86FixupLEAs.cpp 2016-01-23 08:57:43.000000000 -0800
+@@ -190,7 +190,7 @@
+ static inline bool getPreviousInstr(MachineBasicBlock::iterator &I,
+ MachineFunction::iterator MFI) {
+ if (I == MFI->begin()) {
+- if (MFI->isPredecessor(MFI)) {
++ if (MFI->isPredecessor(&*MFI)) {
+ I = --MFI->end();
+ return true;
+ } else
+--- lib/Target/X86/X86FloatingPoint.cpp 2014-11-18 23:49:26.000000000 -0800
++++ lib/Target/X86/X86FloatingPoint.cpp 2016-01-23 09:03:48.000000000 -0800
+@@ -321,7 +321,7 @@
+ // Process the function in depth first order so that we process at least one
+ // of the predecessors for every reachable block in the function.
+ SmallPtrSet<MachineBasicBlock*, 8> Processed;
+- MachineBasicBlock *Entry = MF.begin();
++ MachineBasicBlock *Entry = &MF.front();
+
+ bool Changed = false;
+ for (MachineBasicBlock *BB : depth_first_ext(Entry, Processed))
+@@ -329,9 +329,9 @@
+
+ // Process any unreachable blocks in arbitrary order now.
+ if (MF.size() != Processed.size())
+- for (MachineFunction::iterator BB = MF.begin(), E = MF.end(); BB != E; ++BB)
+- if (Processed.insert(BB).second)
+- Changed |= processBasicBlock(MF, *BB);
++ for (MachineBasicBlock &BB : MF)
++ if (Processed.insert(&BB).second)
++ Changed |= processBasicBlock(MF, BB);
+
+ LiveBundles.clear();
+
+@@ -348,13 +348,12 @@
+ LiveBundles.resize(Bundles->getNumBundles());
+
+ // Gather the actual live-in masks for all MBBs.
+- for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
+- MachineBasicBlock *MBB = I;
+- const unsigned Mask = calcLiveInMask(MBB);
++ for (MachineBasicBlock &MBB : MF) {
++ const unsigned Mask = calcLiveInMask(&MBB);
+ if (!Mask)
+ continue;
+ // Update MBB ingoing bundle mask.
+- LiveBundles[Bundles->getBundle(MBB->getNumber(), false)].Mask |= Mask;
++ LiveBundles[Bundles->getBundle(MBB.getNumber(), false)].Mask |= Mask;
+ }
+ }
+
+--- lib/Target/X86/X86ISelDAGToDAG.cpp 2015-01-05 20:23:53.000000000 -0800
++++ lib/Target/X86/X86ISelDAGToDAG.cpp 2016-01-23 09:08:15.000000000 -0800
+@@ -458,7 +458,8 @@
+
+ for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
+ E = CurDAG->allnodes_end(); I != E; ) {
+- SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
++ SDNode *N = &*I; // Preincrement iterator to avoid invalidation issues.
++ ++I;
+
+ if (OptLevel != CodeGenOpt::None &&
+ // Only does this when target favors doesn't favor register indirect
+@@ -586,7 +587,7 @@
+ // If this is main, emit special code for main.
+ if (const Function *Fn = MF->getFunction())
+ if (Fn->hasExternalLinkage() && Fn->getName() == "main")
+- EmitSpecialCodeForMain(MF->begin(), MF->getFrameInfo());
++ EmitSpecialCodeForMain(&MF->front(), MF->getFrameInfo());
+ }
+
+ static bool isDispSafeForFrameIndex(int64_t Val) {
+@@ -778,7 +779,7 @@
+ static void InsertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
+ if (N.getNode()->getNodeId() == -1 ||
+ N.getNode()->getNodeId() > Pos.getNode()->getNodeId()) {
+- DAG.RepositionNode(Pos.getNode(), N.getNode());
++ DAG.RepositionNode(Pos.getNode()->getIterator(), N.getNode());
+ N.getNode()->setNodeId(Pos.getNode()->getNodeId());
+ }
+ }
+--- lib/Target/X86/X86ISelLowering.cpp 2015-05-01 21:17:29.000000000 -0700
++++ lib/Target/X86/X86ISelLowering.cpp 2016-01-23 10:03:26.000000000 -0800
+@@ -20363,8 +20363,7 @@
+ DebugLoc DL = MI->getDebugLoc();
+
+ const BasicBlock *BB = MBB->getBasicBlock();
+- MachineFunction::iterator I = MBB;
+- ++I;
++ MachineFunction::iterator I = ++MBB->getIterator();
+
+ // For the v = xbegin(), we generate
+ //
+@@ -20613,7 +20612,7 @@
+ offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
+ endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
+
+- MachineFunction::iterator MBBIter = MBB;
++ MachineFunction::iterator MBBIter = ++MBB->getIterator();
+ ++MBBIter;
+
+ // Insert the new basic blocks
+@@ -20784,8 +20783,7 @@
+ // stores were performed.
+ const BasicBlock *LLVM_BB = MBB->getBasicBlock();
+ MachineFunction *F = MBB->getParent();
+- MachineFunction::iterator MBBIter = MBB;
+- ++MBBIter;
++ MachineFunction::iterator MBBIter = ++MBB->getIterator();
+ MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
+ MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
+ F->insert(MBBIter, XMMSaveMBB);
+@@ -20893,8 +20891,7 @@
+ // destination vreg to set, the condition code register to branch on, the
+ // true/false values to select between, and a branch opcode to use.
+ const BasicBlock *LLVM_BB = BB->getBasicBlock();
+- MachineFunction::iterator It = BB;
+- ++It;
++ MachineFunction::iterator It = ++BB->getIterator();
+
+ // thisMBB:
+ // ...
+@@ -20997,8 +20994,7 @@
+ sizeVReg = MI->getOperand(1).getReg(),
+ physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
+
+- MachineFunction::iterator MBBIter = BB;
+- ++MBBIter;
++ MachineFunction::iterator MBBIter = ++BB->getIterator();
+
+ MF->insert(MBBIter, bumpMBB);
+ MF->insert(MBBIter, mallocMBB);
+@@ -21168,8 +21164,7 @@
+ MachineRegisterInfo &MRI = MF->getRegInfo();
+
+ const BasicBlock *BB = MBB->getBasicBlock();
+- MachineFunction::iterator I = MBB;
+- ++I;
++ MachineFunction::iterator I = ++MBB->getIterator();
+
+ // Memory Reference
+ MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
+--- lib/Target/X86/X86PadShortFunction.cpp 2014-08-04 14:25:23.000000000 -0700
++++ lib/Target/X86/X86PadShortFunction.cpp 2016-01-23 10:05:38.000000000 -0800
+@@ -110,7 +110,7 @@
+ // Search through basic blocks and mark the ones that have early returns
+ ReturnBBs.clear();
+ VisitedBBs.clear();
+- findReturns(MF.begin());
++ findReturns(&MF.front());
+
+ bool MadeChange = false;
+
+--- lib/Transforms/IPO/ArgumentPromotion.cpp 2014-12-15 06:09:53.000000000 -0800
++++ lib/Transforms/IPO/ArgumentPromotion.cpp 2015-11-29 18:37:06.014532943 -0800
+@@ -214,7 +214,8 @@
+ SmallVector<Argument*, 16> PointerArgs;
+ for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
+ if (I->getType()->isPointerTy())
+- PointerArgs.push_back(I);
++ PointerArgs.push_back(&*I);
++
+ if (PointerArgs.empty()) return nullptr;
+
+ // Second check: make sure that all callers are direct callers. We can't
+@@ -435,7 +436,8 @@
+
+ // First, iterate the entry block and mark loads of (geps of) arguments as
+ // safe.
+- BasicBlock *EntryBlock = Arg->getParent()->begin();
++ BasicBlock *EntryBlock = &Arg->getParent()->front();
++
+ // Declare this here so we can reuse it
+ IndicesVector Indices;
+ for (BasicBlock::iterator I = EntryBlock->begin(), E = EntryBlock->end();
+@@ -620,14 +622,14 @@
+ unsigned ArgIndex = 1;
+ for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
+ ++I, ++ArgIndex) {
+- if (ByValArgsToTransform.count(I)) {
++ if (ByValArgsToTransform.count(&*I)) {
+ // Simple byval argument? Just add all the struct element types.
+ Type *AgTy = cast<PointerType>(I->getType())->getElementType();
+ StructType *STy = cast<StructType>(AgTy);
+ for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
+ Params.push_back(STy->getElementType(i));
+ ++NumByValArgsPromoted;
+- } else if (!ArgsToPromote.count(I)) {
++ } else if (!ArgsToPromote.count(&*I)) {
+ // Unchanged argument
+ Params.push_back(I->getType());
+ AttributeSet attrs = PAL.getParamAttributes(ArgIndex);
+@@ -645,7 +647,7 @@
+
+ // In this table, we will track which indices are loaded from the argument
+ // (where direct loads are tracked as no indices).
+- ScalarizeTable &ArgIndices = ScalarizedElements[I];
++ ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
+ for (User *U : I->users()) {
+ Instruction *UI = cast<Instruction>(U);
+ assert(isa<LoadInst>(UI) || isa<GetElementPtrInst>(UI));
+@@ -667,7 +669,7 @@
+ else
+ // Take any load, we will use it only to update Alias Analysis
+ OrigLoad = cast<LoadInst>(UI->user_back());
+- OriginalLoads[std::make_pair(I, Indices)] = OrigLoad;
++ OriginalLoads[std::make_pair(&*I, Indices)] = OrigLoad;
+ }
+
+ // Add a parameter to the function for each element passed in.
+@@ -712,19 +714,15 @@
+
+ DEBUG(dbgs() << "ARG PROMOTION: Promoting to:" << *NF << "\n"
+ << "From: " << *F);
+-
++
+ // Recompute the parameter attributes list based on the new arguments for
+ // the function.
+ NF->setAttributes(AttributeSet::get(F->getContext(), AttributesVec));
+ AttributesVec.clear();
+
+- F->getParent()->getFunctionList().insert(F, NF);
++ F->getParent()->getFunctionList().insert(F->getIterator(), NF);
+ NF->takeName(F);
+
+- // Get the alias analysis information that we need to update to reflect our
+- // changes.
+- AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
+-
+ // Get the callgraph information that we need to update to reflect our
+ // changes.
+ CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
+@@ -753,7 +751,7 @@
+ ArgIndex = 1;
+ for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
+ I != E; ++I, ++AI, ++ArgIndex)
+- if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
++ if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) {
+ Args.push_back(*AI); // Unmodified argument
+
+ if (CallPAL.hasAttributes(ArgIndex)) {
+@@ -761,7 +759,7 @@
+ AttributesVec.
+ push_back(AttributeSet::get(F->getContext(), Args.size(), B));
+ }
+- } else if (ByValArgsToTransform.count(I)) {
++ } else if (ByValArgsToTransform.count(&*I)) {
+ // Emit a GEP and load for each element of the struct.
+ Type *AgTy = cast<PointerType>(I->getType())->getElementType();
+ StructType *STy = cast<StructType>(AgTy);
+@@ -777,14 +775,14 @@
+ }
+ } else if (!I->use_empty()) {
+ // Non-dead argument: insert GEPs and loads as appropriate.
+- ScalarizeTable &ArgIndices = ScalarizedElements[I];
++ ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
+ // Store the Value* version of the indices in here, but declare it now
+ // for reuse.
+ std::vector<Value*> Ops;
+ for (ScalarizeTable::iterator SI = ArgIndices.begin(),
+ E = ArgIndices.end(); SI != E; ++SI) {
+ Value *V = *AI;
+- LoadInst *OrigLoad = OriginalLoads[std::make_pair(I, *SI)];
++ LoadInst *OrigLoad = OriginalLoads[std::make_pair(&*I, *SI)];
+ if (!SI->empty()) {
+ Ops.reserve(SI->size());
+ Type *ElTy = V->getType();
+@@ -793,7 +791,7 @@
+ // Use i32 to index structs, and i64 for others (pointers/arrays).
+ // This satisfies GEP constraints.
+ Type *IdxTy = (ElTy->isStructTy() ?
+- Type::getInt32Ty(F->getContext()) :
++ Type::getInt32Ty(F->getContext()) :
+ Type::getInt64Ty(F->getContext()));
+ Ops.push_back(ConstantInt::get(IdxTy, *II));
+ // Keep track of the type we're currently indexing.
+@@ -802,8 +800,8 @@
+ // And create a GEP to extract those indices.
+ V = GetElementPtrInst::Create(V, Ops, V->getName()+".idx", Call);
+ Ops.clear();
+- AA.copyValue(OrigLoad->getOperand(0), V);
+ }
++
+ // Since we're replacing a load make sure we take the alignment
+ // of the previous load.
+ LoadInst *newLoad = new LoadInst(V, V->getName()+".val", Call);
+@@ -814,7 +812,6 @@
+ newLoad->setAAMetadata(AAInfo);
+
+ Args.push_back(newLoad);
+- AA.copyValue(OrigLoad, Args.back());
+ }
+ }
+
+@@ -852,10 +849,6 @@
+ Args.clear();
+ AttributesVec.clear();
+
+- // Update the alias analysis implementation to know that we are replacing
+- // the old call with a new one.
+- AA.replaceWithNewValue(Call, New);
+-
+ // Update the callgraph to know that the callsite has been transformed.
+ CallGraphNode *CalleeNode = CG[Call->getParent()->getParent()];
+ CalleeNode->replaceCallEdge(Call, New, NF_CGN);
+@@ -877,23 +870,21 @@
+
+ // Loop over the argument list, transferring uses of the old arguments over to
+ // the new arguments, also transferring over the names as well.
+- //
+ for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
+ I2 = NF->arg_begin(); I != E; ++I) {
+- if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
++ if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) {
+ // If this is an unmodified argument, move the name and users over to the
+ // new version.
+- I->replaceAllUsesWith(I2);
+- I2->takeName(I);
+- AA.replaceWithNewValue(I, I2);
++ I->replaceAllUsesWith(&*I2);
++ I2->takeName(&*I);
+ ++I2;
+ continue;
+ }
+
+- if (ByValArgsToTransform.count(I)) {
++ if (ByValArgsToTransform.count(&*I)) {
+ // In the callee, we create an alloca, and store each of the new incoming
+ // arguments into the alloca.
+- Instruction *InsertPt = NF->begin()->begin();
++ Instruction *InsertPt = &NF->begin()->front();
+
+ // Just add all the struct element types.
+ Type *AgTy = cast<PointerType>(I->getType())->getElementType();
+@@ -904,18 +895,17 @@
+
+ for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
+ Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
+- Value *Idx =
++ Value *Idx =
+ GetElementPtrInst::Create(TheAlloca, Idxs,
+- TheAlloca->getName()+"."+Twine(i),
++ TheAlloca->getName() + "." + Twine(i),
+ InsertPt);
+- I2->setName(I->getName()+"."+Twine(i));
+- new StoreInst(I2++, Idx, InsertPt);
++ I2->setName(I->getName() + "." +Twine(i));
++ new StoreInst(&*I2++, Idx, InsertPt);
+ }
+
+ // Anything that used the arg should now use the alloca.
+ I->replaceAllUsesWith(TheAlloca);
+- TheAlloca->takeName(I);
+- AA.replaceWithNewValue(I, TheAlloca);
++ TheAlloca->takeName(&*I);
+
+ // If the alloca is used in a call, we must clear the tail flag since
+ // the callee now uses an alloca from the caller.
+@@ -928,23 +918,20 @@
+ continue;
+ }
+
+- if (I->use_empty()) {
+- AA.deleteValue(I);
++ if (I->use_empty())
+ continue;
+- }
+
+ // Otherwise, if we promoted this argument, then all users are load
+ // instructions (or GEPs with only load users), and all loads should be
+ // using the new argument that we added.
+- ScalarizeTable &ArgIndices = ScalarizedElements[I];
++ ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
+
+ while (!I->use_empty()) {
+ if (LoadInst *LI = dyn_cast<LoadInst>(I->user_back())) {
+ assert(ArgIndices.begin()->empty() &&
+ "Load element should sort to front!");
+ I2->setName(I->getName()+".val");
+- LI->replaceAllUsesWith(I2);
+- AA.replaceWithNewValue(LI, I2);
++ LI->replaceAllUsesWith(&*I2);
+ LI->eraseFromParent();
+ DEBUG(dbgs() << "*** Promoted load of argument '" << I->getName()
+ << "' in function '" << F->getName() << "'\n");
+@@ -980,11 +967,10 @@
+ // the argument specified by ArgNo.
+ while (!GEP->use_empty()) {
+ LoadInst *L = cast<LoadInst>(GEP->user_back());
+- L->replaceAllUsesWith(TheArg);
+- AA.replaceWithNewValue(L, TheArg);
++ L->replaceAllUsesWith(&*TheArg);
+ L->eraseFromParent();
+ }
+- AA.deleteValue(GEP);
++
+ GEP->eraseFromParent();
+ }
+ }
+@@ -993,12 +979,9 @@
+ std::advance(I2, ArgIndices.size());
+ }
+
+- // Tell the alias analysis that the old function is about to disappear.
+- AA.replaceWithNewValue(F, NF);
+
+-
+ NF_CGN->stealCalledFunctionsFrom(CG[F]);
+-
++
+ // Now that the old function is dead, delete it. If there is a dangling
+ // reference to the CallgraphNode, just leave the dead function around for
+ // someone else to nuke.
+@@ -1007,7 +990,7 @@
+ delete CG.removeFunctionFromModule(CGN);
+ else
+ F->setLinkage(Function::ExternalLinkage);
+-
++
+ return NF_CGN;
+ }
+
+--- lib/Transforms/IPO/ConstantMerge.cpp 2014-08-20 22:55:13.000000000 -0700
++++ lib/Transforms/IPO/ConstantMerge.cpp 2015-11-29 18:38:45.961868975 -0800
+@@ -130,7 +130,8 @@
+ // First: Find the canonical constants others will be merged with.
+ for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
+ GVI != E; ) {
+- GlobalVariable *GV = GVI++;
++ GlobalVariable *GV = &*GVI;
++ ++GVI;
+
+ // If this GV is dead, remove it.
+ GV->removeDeadConstantUsers();
+@@ -172,7 +173,8 @@
+ // invalidating the Constant* pointers in CMap.
+ for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
+ GVI != E; ) {
+- GlobalVariable *GV = GVI++;
++ GlobalVariable *GV = &*GVI;
++ ++GVI;
+
+ // Only process constants with initializers in the default address space.
+ if (!GV->isConstant() || !GV->hasDefinitiveInitializer() ||
+--- lib/Transforms/IPO/DeadArgumentElimination.cpp 2014-10-07 08:10:23.000000000 -0700
++++ lib/Transforms/IPO/DeadArgumentElimination.cpp 2015-11-29 18:53:45.446590015 -0800
+@@ -229,7 +229,7 @@
+ // Create the new function body and insert it into the module...
+ Function *NF = Function::Create(NFTy, Fn.getLinkage());
+ NF->copyAttributesFrom(&Fn);
+- Fn.getParent()->getFunctionList().insert(&Fn, NF);
++ Fn.getParent()->getFunctionList().insert(Fn.getIterator(), NF);
+ NF->takeName(&Fn);
+
+ // Loop over all of the callers of the function, transforming the call sites
+@@ -296,8 +296,8 @@
+ for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
+ I2 = NF->arg_begin(); I != E; ++I, ++I2) {
+ // Move the name and users over to the new version.
+- I->replaceAllUsesWith(I2);
+- I2->takeName(I);
++ I->replaceAllUsesWith(&*I2);
++ I2->takeName(&*I);
+ }
+
+ // Patch the pointer to LLVM function in debug info descriptor.
+@@ -351,12 +351,10 @@
+ return false;
+
+ SmallVector<unsigned, 8> UnusedArgs;
+- for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
+- I != E; ++I) {
+- Argument *Arg = I;
+
+- if (Arg->use_empty() && !Arg->hasByValOrInAllocaAttr())
+- UnusedArgs.push_back(Arg->getArgNo());
++ for (Argument &Arg : Fn.args()) {
++ if (Arg.use_empty() && !Arg.hasByValOrInAllocaAttr())
++ UnusedArgs.push_back(Arg.getArgNo());
+ }
+
+ if (UnusedArgs.empty())
+@@ -617,7 +615,7 @@
+ } else {
+ // See what the effect of this use is (recording any uses that cause
+ // MaybeLive in MaybeLiveArgUses).
+- Result = SurveyUses(AI, MaybeLiveArgUses);
++ Result = SurveyUses(&*AI, MaybeLiveArgUses);
+ }
+
+ // Mark the result.
+@@ -862,7 +860,7 @@
+ NF->setAttributes(NewPAL);
+ // Insert the new function before the old function, so we won't be processing
+ // it again.
+- F->getParent()->getFunctionList().insert(F, NF);
++ F->getParent()->getFunctionList().insert(F->getIterator(), NF);
+ NF->takeName(F);
+
+ // Loop over all of the callers of the function, transforming the call sites
+@@ -966,7 +964,7 @@
+ if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
+ BasicBlock::iterator IP = II->getNormalDest()->begin();
+ while (isa<PHINode>(IP)) ++IP;
+- InsertPt = IP;
++ InsertPt = &*IP;
+ }
+
+ // We used to return a struct. Instead of doing smart stuff with all the
+@@ -1014,8 +1012,8 @@
+ if (ArgAlive[i]) {
+ // If this is a live argument, move the name and users over to the new
+ // version.
+- I->replaceAllUsesWith(I2);
+- I2->takeName(I);
++ I->replaceAllUsesWith(&*I2);
++ I2->takeName(&*I);
+ ++I2;
+ } else {
+ // If this argument is dead, replace any uses of it with null constants
+@@ -1107,7 +1105,8 @@
+ for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
+ // Increment now, because the function will probably get removed (ie.
+ // replaced by a new one).
+- Function *F = I++;
++ Function *F = &*I;
++ ++I;
+ Changed |= RemoveDeadStuffFromFunction(F);
+ }
+
+--- lib/Transforms/IPO/ExtractGV.cpp 2014-10-28 04:54:52.000000000 -0700
++++ lib/Transforms/IPO/ExtractGV.cpp 2015-11-29 18:57:50.191073612 -0800
+@@ -83,7 +83,7 @@
+ for (Module::global_iterator I = M.global_begin(), E = M.global_end();
+ I != E; ++I) {
+ bool Delete =
+- deleteStuff == (bool)Named.count(I) && !I->isDeclaration();
++ deleteStuff == (bool) Named.count(&*I) && !I->isDeclaration();
+ if (!Delete) {
+ if (I->hasAvailableExternallyLinkage())
+ continue;
+@@ -100,7 +100,7 @@
+ // Visit the Functions.
+ for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
+ bool Delete =
+- deleteStuff == (bool)Named.count(I) && !I->isDeclaration();
++ deleteStuff == (bool) Named.count(&*I) && !I->isDeclaration();
+ if (!Delete) {
+ if (I->hasAvailableExternallyLinkage())
+ continue;
+@@ -108,8 +108,10 @@
+
+ makeVisible(*I, Delete);
+
+- if (Delete)
++ if (Delete) {
+ I->deleteBody();
++ I->setComdat(nullptr);
++ }
+ }
+
+ // Visit the Aliases.
+@@ -118,7 +120,7 @@
+ Module::alias_iterator CurI = I;
+ ++I;
+
+- bool Delete = deleteStuff == (bool)Named.count(CurI);
++ bool Delete = deleteStuff == (bool) Named.count(&*CurI);
+ makeVisible(*CurI, Delete);
+
+ if (Delete) {
+@@ -136,8 +138,9 @@
+ nullptr, CurI->getName());
+
+ }
++
+ CurI->replaceAllUsesWith(Declaration);
+- delete CurI;
++ delete &*CurI;
+ }
+ }
+
+--- lib/Transforms/IPO/FunctionAttrs.cpp 2014-11-18 23:49:26.000000000 -0800
++++ lib/Transforms/IPO/FunctionAttrs.cpp 2015-11-29 19:01:30.757096968 -0800
+@@ -365,7 +365,7 @@
+ return true;
+ }
+ if (PI == U) {
+- Uses.push_back(AI);
++ Uses.push_back(&*AI);
+ Found = true;
+ break;
+ }
+@@ -489,15 +489,19 @@
+ "More params than args in non-varargs call.");
+ return Attribute::None;
+ }
++
+ Captures &= !CS.doesNotCapture(A - B);
+- if (SCCNodes.count(AI))
++ if (SCCNodes.count(&*AI))
+ continue;
++
+ if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(A - B))
+ return Attribute::None;
++
+ if (!CS.doesNotAccessMemory(A - B))
+ IsRead = true;
+ }
+ }
++
+ AddUsersToWorklistIfCapturing();
+ break;
+ }
+@@ -574,7 +578,7 @@
+ bool HasNonLocalUses = false;
+ if (!A->hasNoCaptureAttr()) {
+ ArgumentUsesTracker Tracker(SCCNodes);
+- PointerMayBeCaptured(A, &Tracker);
++ PointerMayBeCaptured(&*A, &Tracker);
+ if (!Tracker.Captured) {
+ if (Tracker.Uses.empty()) {
+ // If it's trivially not captured, mark it nocapture now.
+@@ -585,7 +589,7 @@
+ // If it's not trivially captured and not trivially not captured,
+ // then it must be calling into another function in our SCC. Save
+ // its particulars for Argument-SCC analysis later.
+- ArgumentGraphNode *Node = AG[A];
++ ArgumentGraphNode *Node = AG[&*A];
+ for (SmallVectorImpl<Argument*>::iterator UI = Tracker.Uses.begin(),
+ UE = Tracker.Uses.end(); UI != UE; ++UI) {
+ Node->Uses.push_back(AG[*UI]);
+@@ -602,8 +606,8 @@
+ // will be dependent on the iteration order through the functions in the
+ // SCC.
+ SmallPtrSet<Argument*, 8> Self;
+- Self.insert(A);
+- Attribute::AttrKind R = determinePointerReadAttrs(A, Self);
++ Self.insert(&*A);
++ Attribute::AttrKind R = determinePointerReadAttrs(&*A, Self);
+ if (R != Attribute::None) {
+ AttrBuilder B;
+ B.addAttribute(R);
+--- lib/Transforms/IPO/GlobalDCE.cpp 2014-12-02 18:08:38.000000000 -0800
++++ lib/Transforms/IPO/GlobalDCE.cpp 2015-11-29 19:08:57.774680942 -0800
+@@ -84,7 +84,7 @@
+ // Functions with external linkage are needed if they have a body
+ if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage()) {
+ if (!I->isDiscardableIfUnused())
+- GlobalIsNeeded(I);
++ GlobalIsNeeded(&*I);
+ }
+ }
+
+@@ -95,7 +95,7 @@
+ // initializer.
+ if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage()) {
+ if (!I->isDiscardableIfUnused())
+- GlobalIsNeeded(I);
++ GlobalIsNeeded(&*I);
+ }
+ }
+
+@@ -104,7 +104,7 @@
+ Changed |= RemoveUnusedGlobalValue(*I);
+ // Externally visible aliases are needed.
+ if (!I->isDiscardableIfUnused()) {
+- GlobalIsNeeded(I);
++ GlobalIsNeeded(&*I);
+ }
+ }
+
+@@ -116,8 +116,8 @@
+ std::vector<GlobalVariable*> DeadGlobalVars; // Keep track of dead globals
+ for (Module::global_iterator I = M.global_begin(), E = M.global_end();
+ I != E; ++I)
+- if (!AliveGlobals.count(I)) {
+- DeadGlobalVars.push_back(I); // Keep track of dead globals
++ if (!AliveGlobals.count(&*I)) {
++ DeadGlobalVars.push_back(&*I); // Keep track of dead globals
+ if (I->hasInitializer()) {
+ Constant *Init = I->getInitializer();
+ I->setInitializer(nullptr);
+@@ -129,8 +129,8 @@
+ // The second pass drops the bodies of functions which are dead...
+ std::vector<Function*> DeadFunctions;
+ for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
+- if (!AliveGlobals.count(I)) {
+- DeadFunctions.push_back(I); // Keep track of dead globals
++ if (!AliveGlobals.count(&*I)) {
++ DeadFunctions.push_back(&*I); // Keep track of dead globals
+ if (!I->isDeclaration())
+ I->deleteBody();
+ }
+@@ -139,8 +139,8 @@
+ std::vector<GlobalAlias*> DeadAliases;
+ for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); I != E;
+ ++I)
+- if (!AliveGlobals.count(I)) {
+- DeadAliases.push_back(I);
++ if (!AliveGlobals.count(&*I)) {
++ DeadAliases.push_back(&*I);
+ I->setAliasee(nullptr);
+ }
+
+--- lib/Transforms/IPO/GlobalOpt.cpp 2014-11-18 23:49:26.000000000 -0800
++++ lib/Transforms/IPO/GlobalOpt.cpp 2015-11-29 19:20:51.649538813 -0800
+@@ -493,12 +493,13 @@
+ for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
+ Constant *In = Init->getAggregateElement(i);
+ assert(In && "Couldn't get element of initializer?");
+- GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
+- GlobalVariable::InternalLinkage,
+- In, GV->getName()+"."+Twine(i),
+- GV->getThreadLocalMode(),
+- GV->getType()->getAddressSpace());
+- Globals.insert(GV, NGV);
++ GlobalVariable *NGV =
++ new GlobalVariable(STy->getElementType(i), false,
++ GlobalVariable::InternalLinkage,
++ In, GV->getName()+"."+Twine(i),
++ GV->getThreadLocalMode(),
++ GV->getType()->getAddressSpace());
++ Globals.insert(GV->getIterator(), NGV);
+ NewGlobals.push_back(NGV);
+
+ // Calculate the known alignment of the field. If theinal aggregate
+@@ -526,12 +527,13 @@
+ Constant *In = Init->getAggregateElement(i);
+ assert(In && "Couldn't get element of initializer?");
+
+- GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
+- GlobalVariable::InternalLinkage,
+- In, GV->getName()+"."+Twine(i),
+- GV->getThreadLocalMode(),
+- GV->getType()->getAddressSpace());
+- Globals.insert(GV, NGV);
++ GlobalVariable *NGV =
++ new GlobalVariable(STy->getElementType(), false,
++ GlobalVariable::InternalLinkage,
++ In, GV->getName()+"."+Twine(i),
++ GV->getThreadLocalMode(),
++ GV->getType()->getAddressSpace());
++ Globals.insert(GV->getIterator(), NGV);
+ NewGlobals.push_back(NGV);
+
+ // Calculate the known alignment of the field. If theinal aggregate
+@@ -936,7 +938,7 @@
+ cast<StoreInst>(InitBool->user_back())->eraseFromParent();
+ delete InitBool;
+ } else
+- GV->getParent()->getGlobalList().insert(GV, InitBool);
++ GV->getParent()->getGlobalList().insert(GV->getIterator(), InitBool);
+
+ // Now the GV is dead, nuke it and the malloc..
+ GV->eraseFromParent();
+@@ -1338,7 +1340,8 @@
+
+ // Split the basic block at the old malloc.
+ BasicBlock *OrigBB = CI->getParent();
+- BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
++ BasicBlock *ContBB =
++ OrigBB->splitBasicBlock(CI->getIterator(), "malloc_cont");
+
+ // Create the block to check the first condition. Put all these blocks at the
+ // end of the function as they are unlikely to be executed.
+@@ -1505,7 +1508,8 @@
+ // (2048 bytes currently), as we don't want to introduce a 16M global or
+ // something.
+ if (NElements->getZExtValue() * DL->getTypeAllocSize(AllocTy) < 2048) {
+- GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, DL, TLI);
++ GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy,
++ NElements, DL, TLI)->getIterator();
+ return true;
+ }
+
+@@ -1551,7 +1555,7 @@
+ }
+
+ GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, DL, TLI, true),
+- DL, TLI);
++ DL, TLI)->getIterator();
+ return true;
+ }
+
+@@ -1626,7 +1630,7 @@
+ GV->getName()+".b",
+ GV->getThreadLocalMode(),
+ GV->getType()->getAddressSpace());
+- GV->getParent()->getGlobalList().insert(GV, NewGV);
++ GV->getParent()->getGlobalList().insert(GV->getIterator(), NewGV);
+
+ Constant *InitVal = GV->getInitializer();
+ assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
+@@ -1807,7 +1811,7 @@
+ if (DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>()) {
+ const DataLayout &DL = DLP->getDataLayout();
+ if (GlobalVariable *FirstNewGV = SRAGlobal(GV, DL)) {
+- GVI = FirstNewGV; // Don't skip the newly produced globals!
++ GVI = FirstNewGV->getIterator(); // Don't skip the newly produced globals!
+ return true;
+ }
+ }
+@@ -1830,7 +1834,7 @@
+ GV->eraseFromParent();
+ ++NumDeleted;
+ } else {
+- GVI = GV;
++ GVI = GV->getIterator();
+ }
+ ++NumSubstitute;
+ return true;
+@@ -1905,7 +1909,7 @@
+ bool Changed = false;
+ // Optimize functions.
+ for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
+- Function *F = FI++;
++ Function *F = &*FI++;
+ // Functions without names cannot be referenced outside this module.
+ if (!F->hasName() && !F->isDeclaration() && !F->hasLocalLinkage())
+ F->setLinkage(GlobalValue::InternalLinkage);
+@@ -1947,7 +1951,7 @@
+
+ for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
+ GVI != E; ) {
+- GlobalVariable *GV = GVI++;
++ GlobalVariable *GV = &*GVI++;
+ // Global variables without names cannot be referenced outside this module.
+ if (!GV->hasName() && !GV->isDeclaration() && !GV->hasLocalLinkage())
+ GV->setLinkage(GlobalValue::InternalLinkage);
+@@ -2446,7 +2450,7 @@
+ InstResult = AllocaTmps.back().get();
+ DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
+ } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
+- CallSite CS(CurInst);
++ CallSite CS(&*CurInst);
+
+ // Debug info can safely be ignored here.
+ if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
+@@ -2608,7 +2612,7 @@
+ if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
+ InstResult = ConstantFoldConstantExpression(CE, DL, TLI);
+
+- setVal(CurInst, InstResult);
++ setVal(&*CurInst, InstResult);
+ }
+
+ // If we just processed an invoke, we finished evaluating the block.
+@@ -2639,7 +2643,7 @@
+ unsigned ArgNo = 0;
+ for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
+ ++AI, ++ArgNo)
+- setVal(AI, ActualArgs[ArgNo]);
++ setVal(&*AI, ActualArgs[ArgNo]);
+
+ // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
+ // we can only evaluate any one basic block at most once. This set keeps
+@@ -2647,7 +2651,7 @@
+ SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
+
+ // CurBB - The current basic block we're evaluating.
+- BasicBlock *CurBB = F->begin();
++ BasicBlock *CurBB = &F->front();
+
+ BasicBlock::iterator CurInst = CurBB->begin();
+
+@@ -2897,15 +2901,15 @@
+
+ if (RenameTarget) {
+ // Give the aliasee the name, linkage and other attributes of the alias.
+- Target->takeName(J);
++ Target->takeName(&*J);
+ Target->setLinkage(J->getLinkage());
+ Target->setVisibility(J->getVisibility());
+ Target->setDLLStorageClass(J->getDLLStorageClass());
+
+- if (Used.usedErase(J))
++ if (Used.usedErase(&*J))
+ Used.usedInsert(Target);
+
+- if (Used.compilerUsedErase(J))
++ if (Used.compilerUsedErase(&*J))
+ Used.compilerUsedInsert(Target);
+ } else if (mayHaveOtherReferences(*J, Used))
+ continue;
+--- lib/Transforms/IPO/Internalize.cpp 2014-08-24 16:23:06.000000000 -0700
++++ lib/Transforms/IPO/Internalize.cpp 2015-11-29 19:22:14.785278600 -0800
+@@ -162,7 +162,7 @@
+
+ if (ExternalNode)
+ // Remove a callgraph edge from the external node to this function.
+- ExternalNode->removeOneAbstractEdgeTo((*CG)[I]);
++ ExternalNode->removeOneAbstractEdgeTo((*CG)[&*I]);
+
+ Changed = true;
+ ++NumFunctions;
+--- lib/Transforms/IPO/LoopExtractor.cpp 2014-07-21 10:06:51.000000000 -0700
++++ lib/Transforms/IPO/LoopExtractor.cpp 2015-11-29 19:23:56.327652268 -0800
+@@ -259,7 +259,7 @@
+ // Figure out which index the basic block is in its function.
+ Function::iterator BBI = MF->begin();
+ std::advance(BBI, std::distance(F->begin(), Function::iterator(BB)));
+- TranslatedBlocksToNotExtract.insert(BBI);
++ TranslatedBlocksToNotExtract.insert(&*BBI);
+ }
+
+ while (!BlocksToNotExtractByName.empty()) {
+@@ -278,7 +278,7 @@
+ BasicBlock &BB = *BI;
+ if (BB.getName() != BlockName) continue;
+
+- TranslatedBlocksToNotExtract.insert(BI);
++ TranslatedBlocksToNotExtract.insert(&*BI);
+ }
+ }
+
+@@ -291,8 +291,8 @@
+ for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
+ SplitLandingPadPreds(&*F);
+ for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
+- if (!TranslatedBlocksToNotExtract.count(BB))
+- BlocksToExtract.push_back(BB);
++ if (!TranslatedBlocksToNotExtract.count(&*BB))
++ BlocksToExtract.push_back(&*BB);
+ }
+
+ for (unsigned i = 0, e = BlocksToExtract.size(); i != e; ++i) {
+--- lib/Transforms/IPO/MergeFunctions.cpp 2014-11-18 23:49:26.000000000 -0800
++++ lib/Transforms/IPO/MergeFunctions.cpp 2015-11-29 19:32:19.065098905 -0800
+@@ -929,7 +929,7 @@
+ BasicBlock::const_iterator InstR = BBR->begin(), InstRE = BBR->end();
+
+ do {
+- if (int Res = cmpValues(InstL, InstR))
++ if (int Res = cmpValues(&*InstL, &*InstR))
+ return Res;
+
+ const GetElementPtrInst *GEPL = dyn_cast<GetElementPtrInst>(InstL);
+@@ -947,7 +947,7 @@
+ if (int Res = cmpGEPs(GEPL, GEPR))
+ return Res;
+ } else {
+- if (int Res = cmpOperations(InstL, InstR))
++ if (int Res = cmpOperations(&*InstL, &*InstR))
+ return Res;
+ assert(InstL->getNumOperands() == InstR->getNumOperands());
+
+@@ -1019,7 +1019,7 @@
+ ArgRI = FnR->arg_begin(),
+ ArgLE = FnL->arg_end();
+ ArgLI != ArgLE; ++ArgLI, ++ArgRI) {
+- if (cmpValues(ArgLI, ArgRI) != 0)
++ if (cmpValues(&*ArgLI, &*ArgRI) != 0)
+ llvm_unreachable("Arguments repeat!");
+ }
+
+@@ -1217,7 +1217,7 @@
+
+ for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
+ if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage())
+- Deferred.push_back(WeakVH(I));
++ Deferred.push_back(WeakVH(&*I));
+ }
+
+ do {
+@@ -1342,7 +1342,7 @@
+ FunctionType *FFTy = F->getFunctionType();
+ for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
+ AI != AE; ++AI) {
+- Args.push_back(createCast(Builder, (Value*)AI, FFTy->getParamType(i)));
++ Args.push_back(createCast(Builder, &*AI, FFTy->getParamType(i)));
+ ++i;
+ }
+
+--- lib/Transforms/IPO/PartialInlining.cpp 2014-07-21 10:06:51.000000000 -0700
++++ lib/Transforms/IPO/PartialInlining.cpp 2015-11-30 05:52:13.004988742 -0800
+@@ -50,7 +50,7 @@
+
+ Function* PartialInliner::unswitchFunction(Function* F) {
+ // First, verify that this function is an unswitching candidate...
+- BasicBlock* entryBlock = F->begin();
++ BasicBlock* entryBlock = &F->front();
+ BranchInst *BR = dyn_cast<BranchInst>(entryBlock->getTerminator());
+ if (!BR || BR->isUnconditional())
+ return nullptr;
+@@ -88,10 +88,10 @@
+ // sequence of PHIs, some of which will go in the extracted region, and some
+ // of which will go outside.
+ BasicBlock* preReturn = newReturnBlock;
+- newReturnBlock = newReturnBlock->splitBasicBlock(
+- newReturnBlock->getFirstNonPHI());
++ newReturnBlock =
++ newReturnBlock->splitBasicBlock(newReturnBlock->getFirstNonPHI()->getIterator());
+ BasicBlock::iterator I = preReturn->begin();
+- BasicBlock::iterator Ins = newReturnBlock->begin();
++ Instruction *Ins = &newReturnBlock->front();
+ while (I != preReturn->end()) {
+ PHINode* OldPhi = dyn_cast<PHINode>(I);
+ if (!OldPhi) break;
+@@ -100,7 +100,7 @@
+ OldPhi->replaceAllUsesWith(retPhi);
+ Ins = newReturnBlock->getFirstNonPHI();
+
+- retPhi->addIncoming(I, preReturn);
++ retPhi->addIncoming(&*I, preReturn);
+ retPhi->addIncoming(OldPhi->getIncomingValueForBlock(newEntryBlock),
+ newEntryBlock);
+ OldPhi->removeIncomingValue(newEntryBlock);
+@@ -116,7 +116,7 @@
+ FE = duplicateFunction->end(); FI != FE; ++FI)
+ if (&*FI != newEntryBlock && &*FI != newReturnBlock &&
+ &*FI != newNonReturnBlock)
+- toExtract.push_back(FI);
++ toExtract.push_back(&*FI);
+
+ // The CodeExtractor needs a dominator tree.
+ DominatorTree DT;
+--- lib/Transforms/IPO/PruneEH.cpp 2015-01-12 19:46:47.000000000 -0800
++++ lib/Transforms/IPO/PruneEH.cpp 2015-11-30 05:53:43.868963013 -0800
+@@ -218,7 +218,7 @@
+
+ // Remove the uncond branch and add an unreachable.
+ BB->getInstList().pop_back();
+- new UnreachableInst(BB->getContext(), BB);
++ new UnreachableInst(BB->getContext(), &*BB);
+
+ DeleteBasicBlock(New); // Delete the new BB.
+ MadeChange = true;
+--- lib/Transforms/IPO/StripDeadPrototypes.cpp 2014-04-21 19:55:47.000000000 -0700
++++ lib/Transforms/IPO/StripDeadPrototypes.cpp 2015-11-30 05:54:57.769272028 -0800
+@@ -47,7 +47,9 @@
+
+ // Erase dead function prototypes.
+ for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
+- Function *F = I++;
++ Function *F = &*I;
++ ++I;
++
+ // Function must be a prototype and unused.
+ if (F->isDeclaration() && F->use_empty()) {
+ F->eraseFromParent();
+@@ -59,7 +61,9 @@
+ // Erase dead global var prototypes.
+ for (Module::global_iterator I = M.global_begin(), E = M.global_end();
+ I != E; ) {
+- GlobalVariable *GV = I++;
++ GlobalVariable *GV = &*I;
++ ++I;
++
+ // Global must be a prototype and unused.
+ if (GV->isDeclaration() && GV->use_empty())
+ GV->eraseFromParent();
+--- lib/Transforms/IPO/StripSymbols.cpp 2014-12-09 10:38:53.000000000 -0800
++++ lib/Transforms/IPO/StripSymbols.cpp 2015-11-30 06:01:52.193630900 -0800
+@@ -211,13 +211,13 @@
+
+ for (Module::global_iterator I = M.global_begin(), E = M.global_end();
+ I != E; ++I) {
+- if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
++ if (I->hasLocalLinkage() && llvmUsedValues.count(&*I) == 0)
+ if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
+ I->setName(""); // Internal symbols can't participate in linkage
+ }
+
+ for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
+- if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
++ if (I->hasLocalLinkage() && llvmUsedValues.count(&*I) == 0)
+ if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
+ I->setName(""); // Internal symbols can't participate in linkage
+ StripSymtab(I->getValueSymbolTable(), PreserveDbgInfo);
+--- lib/Transforms/InstCombine/InstCombineCalls.cpp 2015-01-22 11:40:47.000000000 -0800
++++ lib/Transforms/InstCombine/InstCombineCalls.cpp 2015-11-30 06:53:40.815329138 -0800
+@@ -1010,15 +1010,14 @@
+ // happen when variable allocas are DCE'd.
+ if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
+ if (SS->getIntrinsicID() == Intrinsic::stacksave) {
+- BasicBlock::iterator BI = SS;
+- if (&*++BI == II)
++ if (&*++SS->getIterator() == II)
+ return EraseInstFromFunction(CI);
+ }
+ }
+
+ // Scan down this block to see if there is another stack restore in the
+ // same block without an intervening call/alloca.
+- BasicBlock::iterator BI = II;
++ BasicBlock::iterator BI(II);
+ TerminatorInst *TI = II->getParent()->getTerminator();
+ bool CannotRemove = false;
+ for (++BI; &*BI != TI; ++BI) {
+@@ -1235,9 +1234,9 @@
+ Value *TrampMem) {
+ // Visit all the previous instructions in the basic block, and try to find a
+ // init.trampoline which has a direct path to the adjust.trampoline.
+- for (BasicBlock::iterator I = AdjustTramp,
++ for (BasicBlock::iterator I = AdjustTramp->getIterator(),
+ E = AdjustTramp->getParent()->begin(); I != E; ) {
+- Instruction *Inst = --I;
++ Instruction *Inst = &*--I;
+ if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
+ if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
+ II->getOperand(0) == TrampMem)
+--- lib/Transforms/InstCombine/InstCombineCasts.cpp 2014-12-12 10:48:37.000000000 -0800
++++ lib/Transforms/InstCombine/InstCombineCasts.cpp 2015-11-30 07:19:19.812837233 -0800
+@@ -86,7 +86,7 @@
+ PointerType *PTy = cast<PointerType>(CI.getType());
+
+ BuilderTy AllocaBuilder(*Builder);
+- AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
++ AllocaBuilder.SetInsertPoint(&AI);
+
+ // Get the type really allocated and the type casted to.
+ Type *AllocElTy = AI.getAllocatedType();
+--- lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cpp 2015-02-12 19:19:15.000000000 -0800
++++ lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cpp 2015-11-30 07:27:36.109476800 -0800
+@@ -187,8 +187,9 @@
+ // Scan to the end of the allocation instructions, to skip over a block of
+ // allocas if possible...also skip interleaved debug info
+ //
+- BasicBlock::iterator It = New;
+- while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
++ BasicBlock::iterator It(New);
++ while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
++ ++It;
+
+ // Now that I is pointing to the first non-allocation-inst in the block,
+ // insert our getelementptr instruction...
+@@ -419,7 +420,7 @@
+ // Do really simple store-to-load forwarding and load CSE, to catch cases
+ // where there are several consecutive memory accesses to the same location,
+ // separated by a few arithmetic operations.
+- BasicBlock::iterator BBI = &LI;
++ BasicBlock::iterator BBI(LI);
+ if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
+ return ReplaceInstUsesWith(
+ LI, Builder->CreateBitOrPointerCast(AvailableVal, LI.getType(),
+@@ -644,7 +645,7 @@
+ // Do really simple DSE, to catch cases where there are several consecutive
+ // stores to the same location, separated by a few arithmetic operations. This
+ // situation often occurs with bitfield accesses.
+- BasicBlock::iterator BBI = &SI;
++ BasicBlock::iterator BBI(SI);
+ for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
+ --ScanInsts) {
+ --BBI;
+@@ -703,7 +704,7 @@
+ // If this store is the last instruction in the basic block (possibly
+ // excepting debug info instructions), and if the block ends with an
+ // unconditional branch, try to move it to the successor block.
+- BBI = &SI;
++ BBI = SI.getIterator();
+ do {
+ ++BBI;
+ } while (isa<DbgInfoIntrinsic>(BBI) ||
+@@ -759,7 +760,7 @@
+ return false;
+
+ // Verify that the other block ends in a branch and is not otherwise empty.
+- BasicBlock::iterator BBI = OtherBB->getTerminator();
++ BasicBlock::iterator BBI(OtherBB->getTerminator());
+ BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
+ if (!OtherBr || BBI == OtherBB->begin())
+ return false;
+--- lib/Transforms/InstCombine/InstCombineMulDivRem.cpp 2015-01-04 04:03:27.000000000 -0800
++++ lib/Transforms/InstCombine/InstCombineMulDivRem.cpp 2015-11-30 07:30:31.455813053 -0800
+@@ -736,7 +736,7 @@
+ return true;
+
+ // Scan the current block backward, looking for other uses of SI.
+- BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
++ BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
+
+ while (BBI != BBFront) {
+ --BBI;
+@@ -750,10 +750,10 @@
+ I != E; ++I) {
+ if (*I == SI) {
+ *I = SI->getOperand(NonNullOperand);
+- Worklist.Add(BBI);
++ Worklist.Add(&*BBI);
+ } else if (*I == SelectCond) {
+ *I = Builder->getInt1(NonNullOperand == 1);
+- Worklist.Add(BBI);
++ Worklist.Add(&*BBI);
+ }
+ }
+
+--- lib/Transforms/InstCombine/InstCombinePHI.cpp 2015-01-04 04:03:27.000000000 -0800
++++ lib/Transforms/InstCombine/InstCombinePHI.cpp 2015-11-30 07:32:38.250246960 -0800
+@@ -247,7 +247,7 @@
+ /// non-address-taken alloca. Doing so will cause us to not promote the alloca
+ /// to a register.
+ static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
+- BasicBlock::iterator BBI = L, E = L->getParent()->end();
++ BasicBlock::iterator BBI = L->getIterator(), E = L->getParent()->end();
+
+ for (++BBI; BBI != E; ++BBI)
+ if (BBI->mayWriteToMemory())
+@@ -744,7 +744,7 @@
+ }
+
+ // Otherwise, do an extract in the predecessor.
+- Builder->SetInsertPoint(Pred, Pred->getTerminator());
++ Builder->SetInsertPoint(Pred->getTerminator());
+ Value *Res = InVal;
+ if (Offset)
+ Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
+--- lib/Transforms/InstCombine/InstCombineVectorOps.cpp 2014-07-07 15:13:58.000000000 -0700
++++ lib/Transforms/InstCombine/InstCombineVectorOps.cpp 2015-11-30 07:47:54.223248158 -0800
+@@ -162,8 +162,7 @@
+ Instruction *pos = dyn_cast<Instruction>(PHIInVal);
+ BasicBlock::iterator InsertPos;
+ if (pos && !isa<PHINode>(pos)) {
+- InsertPos = pos;
+- ++InsertPos;
++ InsertPos = ++pos->getIterator();
+ } else {
+ InsertPos = inBB->getFirstInsertionPt();
+ }
+--- lib/Transforms/InstCombine/InstCombine.h 2015-01-06 16:39:50.000000000 -0800
++++ lib/Transforms/InstCombine/InstCombine.h 2015-11-30 06:47:44.140493020 -0800
+@@ -297,7 +297,7 @@
+ assert(New && !New->getParent() &&
+ "New instruction already inserted into a basic block!");
+ BasicBlock *BB = Old.getParent();
+- BB->getInstList().insert(&Old, New); // Insert inst
++ BB->getInstList().insert(Old.getIterator(), New); // Insert inst
+ Worklist.Add(New);
+ return New;
+ }
+--- lib/Transforms/InstCombine/InstructionCombining.cpp 2015-01-04 04:03:27.000000000 -0800
++++ lib/Transforms/InstCombine/InstructionCombining.cpp 2015-11-30 09:32:37.959104590 -0800
+@@ -1417,13 +1417,13 @@
+ if (DI == -1) {
+ // All the GEPs feeding the PHI are identical. Clone one down into our
+ // BB so that it can be merged with the current GEP.
+- GEP.getParent()->getInstList().insert(GEP.getParent()->getFirstNonPHI(),
+- NewGEP);
++ GEP.getParent()->getInstList().insert(
++ GEP.getParent()->getFirstNonPHI()->getIterator(), NewGEP);
+ } else {
+ // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
+ // into the current block so it can be merged, and create a new PHI to
+ // set that index.
+- Instruction *InsertPt = Builder->GetInsertPoint();
++ Instruction *InsertPt = &*Builder->GetInsertPoint();
+ Builder->SetInsertPoint(PN);
+ PHINode *NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
+ PN->getNumOperands());
+@@ -1434,8 +1434,8 @@
+ PN->getIncomingBlock(I));
+
+ NewGEP->setOperand(DI, NewPN);
+- GEP.getParent()->getInstList().insert(GEP.getParent()->getFirstNonPHI(),
+- NewGEP);
++ GEP.getParent()->getInstList().insert(
++ GEP.getParent()->getFirstNonPHI()->getIterator(), NewGEP);
+ NewGEP->setOperand(DI, NewPN);
+ }
+
+@@ -1768,7 +1768,7 @@
+ if (Instruction *I = visitBitCast(*BCI)) {
+ if (I != BCI) {
+ I->takeName(BCI);
+- BCI->getParent()->getInstList().insert(BCI, I);
++ BCI->getParent()->getInstList().insert(BCI->getIterator(), I);
+ ReplaceInstUsesWith(*BCI, I);
+ }
+ return &GEP;
+@@ -2269,7 +2269,7 @@
+
+ // We need to insert these at the location of the old load, not at that of
+ // the extractvalue.
+- Builder->SetInsertPoint(L->getParent(), L);
++ Builder->SetInsertPoint(L);
+ Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices);
+ // Returning the load directly will cause the main loop to insert it in
+ // the wrong spot, so use ReplaceInstUsesWith().
+@@ -2648,14 +2648,14 @@
+ // We can only sink load instructions if there is nothing between the load and
+ // the end of block that could change the value.
+ if (I->mayReadFromMemory()) {
+- for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
+- Scan != E; ++Scan)
++ for (BasicBlock::iterator Scan = I->getIterator(),
++ E = I->getParent()->end(); Scan != E; ++Scan)
+ if (Scan->mayWriteToMemory())
+ return false;
+ }
+
+ BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
+- I->moveBefore(InsertPos);
++ I->moveBefore(&*InsertPos);
+ ++NumSunkInst;
+ return true;
+ }
+@@ -2690,7 +2690,8 @@
+ continue;
+
+ for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
+- Instruction *Inst = BBI++;
++ Instruction *Inst = &*BBI;
++ ++BBI;
+
+ // DCE instruction if trivially dead.
+ if (isInstructionTriviallyDead(Inst, TLI)) {
+@@ -2787,22 +2788,21 @@
+ // the reachable instructions. Ignore blocks that are not reachable. Keep
+ // track of which blocks we visit.
+ SmallPtrSet<BasicBlock*, 64> Visited;
+- MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, DL,
++ MadeIRChange |= AddReachableCodeToWorklist(&F.front(), Visited, *this, DL,
+ TLI);
+
+ // Do a quick scan over the function. If we find any blocks that are
+ // unreachable, remove any instructions inside of them. This prevents
+ // the instcombine code from having to deal with some bad special cases.
+ for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
+- if (Visited.count(BB)) continue;
++ if (Visited.count(&*BB)) continue;
+
+ // Delete the instructions backwards, as it has a reduced likelihood of
+ // having to update as many def-use and use-def chains.
+ Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
+ while (EndInst != BB->begin()) {
+ // Delete the next to last instruction.
+- BasicBlock::iterator I = EndInst;
+- Instruction *Inst = --I;
++ Instruction *Inst = &*--EndInst->getIterator();
+ if (!Inst->use_empty())
+ Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
+ if (isa<LandingPadInst>(Inst)) {
+@@ -2884,7 +2884,7 @@
+ }
+
+ // Now that we have an instruction, try combining it to simplify it.
+- Builder->SetInsertPoint(I->getParent(), I);
++ Builder->SetInsertPoint(I);
+ Builder->SetCurrentDebugLocation(I->getDebugLoc());
+
+ #ifndef NDEBUG
+@@ -2914,7 +2914,7 @@
+
+ // Insert the new instruction into the basic block...
+ BasicBlock *InstParent = I->getParent();
+- BasicBlock::iterator InsertPos = I;
++ BasicBlock::iterator InsertPos = I->getIterator();
+
+ // If we replace a PHI with something that isn't a PHI, fix up the
+ // insertion point.
+--- lib/Transforms/Instrumentation/AddressSanitizer.cpp 2015-02-03 10:58:33.000000000 -0800
++++ lib/Transforms/Instrumentation/AddressSanitizer.cpp 2016-01-23 20:36:01.000000000 -0800
+@@ -158,10 +158,11 @@
+ "this number of memory accesses, use callbacks instead of "
+ "inline checks (-1 means never use callbacks)."),
+ cl::Hidden, cl::init(7000));
++static std::string AsanInitString("__asan_");
+ static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
+ "asan-memory-access-callback-prefix",
+ cl::desc("Prefix for memory access callbacks"), cl::Hidden,
+- cl::init("__asan_"));
++ cl::init(AsanInitString));
+ static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
+ cl::desc("instrument dynamic allocas"), cl::Hidden, cl::init(false));
+
+@@ -1007,7 +1008,8 @@
+ void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
+ GlobalValue *ModuleName) {
+ // Set up the arguments to our poison/unpoison functions.
+- IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
++ IRBuilder<> IRB(&GlobalInit.front(),
++ GlobalInit.front().getFirstInsertionPt());
+
+ // Add a call to poison all external globals before the given function starts.
+ Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
+@@ -1402,7 +1404,7 @@
+ // We cannot just ignore these methods, because they may call other
+ // instrumented functions.
+ if (F.getName().find(" load]") != std::string::npos) {
+- IRBuilder<> IRB(F.begin()->begin());
++ IRBuilder<> IRB(&F.front(), F.front().begin());
+ IRB.CreateCall(AsanInitFunction);
+ return true;
+ }
+--- lib/Transforms/Instrumentation/BoundsChecking.cpp 2014-04-24 22:29:35.000000000 -0700
++++ lib/Transforms/Instrumentation/BoundsChecking.cpp 2015-11-30 11:29:13.966151410 -0800
+@@ -108,7 +108,7 @@
+ }
+ ++ChecksAdded;
+
+- Instruction *Inst = Builder->GetInsertPoint();
++ BasicBlock::iterator Inst = Builder->GetInsertPoint();
+ BasicBlock *OldBB = Inst->getParent();
+ BasicBlock *Cont = OldBB->splitBasicBlock(Inst);
+ OldBB->getTerminator()->eraseFromParent();
+--- lib/Transforms/Instrumentation/DataFlowSanitizer.cpp 2014-12-05 13:22:32.000000000 -0800
++++ lib/Transforms/Instrumentation/DataFlowSanitizer.cpp 2015-11-30 13:39:14.566562460 -0800
+@@ -580,7 +580,7 @@
+ DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
+ Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
+ for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
+- DFSF.ValShadowMap[ValAI] = ShadowAI;
++ DFSF.ValShadowMap[&*ValAI] = &*ShadowAI;
+ DFSanVisitor(DFSF).visitCallInst(*CI);
+ if (!FT->getReturnType()->isVoidTy())
+ new StoreInst(DFSF.getShadow(RI->getReturnValue()),
+@@ -648,16 +648,16 @@
+
+ std::vector<Function *> FnsToInstrument;
+ llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
+- for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
+- if (!i->isIntrinsic() &&
+- i != DFSanUnionFn &&
+- i != DFSanCheckedUnionFn &&
+- i != DFSanUnionLoadFn &&
+- i != DFSanUnimplementedFn &&
+- i != DFSanSetLabelFn &&
+- i != DFSanNonzeroLabelFn &&
+- i != DFSanVarargWrapperFn)
+- FnsToInstrument.push_back(&*i);
++ for (Function &i : M) {
++ if (!i.isIntrinsic() &&
++ &i != DFSanUnionFn &&
++ &i != DFSanCheckedUnionFn &&
++ &i != DFSanUnionLoadFn &&
++ &i != DFSanUnimplementedFn &&
++ &i != DFSanSetLabelFn &&
++ &i != DFSanNonzeroLabelFn &&
++ &i != DFSanVarargWrapperFn)
++ FnsToInstrument.push_back(&i);
+ }
+
+ // Give function aliases prefixes when necessary, and build wrappers where the
+@@ -715,7 +715,7 @@
+ NewFArg = NewF->arg_begin(),
+ FArgEnd = F.arg_end();
+ FArg != FArgEnd; ++FArg, ++NewFArg) {
+- FArg->replaceAllUsesWith(NewFArg);
++ FArg->replaceAllUsesWith(&*NewFArg);
+ }
+ NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
+
+@@ -847,7 +847,7 @@
+ if (Instruction *I = dyn_cast<Instruction>(V))
+ Pos = I->getNextNode();
+ else
+- Pos = DFSF.F->getEntryBlock().begin();
++ Pos = &DFSF.F->getEntryBlock().front();
+ while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
+ Pos = Pos->getNextNode();
+ IRBuilder<> IRB(Pos);
+@@ -869,7 +869,7 @@
+ if (DFS.ArgTLS)
+ return ArgTLSPtr = DFS.ArgTLS;
+
+- IRBuilder<> IRB(F->getEntryBlock().begin());
++ IRBuilder<> IRB(&F->getEntryBlock().front());
+ return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
+ }
+
+@@ -879,7 +879,7 @@
+ if (DFS.RetvalTLS)
+ return RetvalTLSPtr = DFS.RetvalTLS;
+
+- IRBuilder<> IRB(F->getEntryBlock().begin());
++ IRBuilder<> IRB(&F->getEntryBlock().front());
+ return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
+ }
+
+@@ -911,7 +911,7 @@
+ Function::arg_iterator i = F->arg_begin();
+ while (ArgIdx--)
+ ++i;
+- Shadow = i;
++ Shadow = &*i;
+ assert(Shadow->getType() == DFS.ShadowTy);
+ break;
+ }
+@@ -996,7 +996,7 @@
+ Call->addAttribute(2, Attribute::ZExt);
+
+ BasicBlock *Tail = BI->getSuccessor(0);
+- PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", Tail->begin());
++ PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
+ Phi->addIncoming(Call, Call->getParent());
+ Phi->addIncoming(V1, Head);
+
+@@ -1109,7 +1109,7 @@
+ Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
+
+ BasicBlock *Head = Pos->getParent();
+- BasicBlock *Tail = Head->splitBasicBlock(Pos);
++ BasicBlock *Tail = Head->splitBasicBlock(Pos->getIterator());
+
+ if (DomTreeNode *OldNode = DT.getNode(Head)) {
+ std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
+@@ -1476,7 +1476,7 @@
+ auto LabelVAAlloca =
+ new AllocaInst(ArrayType::get(DFSF.DFS.ShadowTy,
+ CS.arg_size() - FT->getNumParams()),
+- "labelva", DFSF.F->getEntryBlock().begin());
++ "labelva", &DFSF.F->getEntryBlock().front());
+
+ for (unsigned n = 0; i != CS.arg_end(); ++i, ++n) {
+ auto LabelVAPtr = IRB.CreateStructGEP(LabelVAAlloca, n);
+@@ -1490,7 +1490,7 @@
+ if (!DFSF.LabelReturnAlloca) {
+ DFSF.LabelReturnAlloca =
+ new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
+- DFSF.F->getEntryBlock().begin());
++ &DFSF.F->getEntryBlock().front());
+ }
+ Args.push_back(DFSF.LabelReturnAlloca);
+ }
+@@ -1529,11 +1529,11 @@
+ if (!CS.getType()->isVoidTy()) {
+ if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
+ if (II->getNormalDest()->getSinglePredecessor()) {
+- Next = II->getNormalDest()->begin();
++ Next = &II->getNormalDest()->front();
+ } else {
+ BasicBlock *NewBB =
+ SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS);
+- Next = NewBB->begin();
++ Next = &NewBB->front();
+ }
+ } else {
+ Next = CS->getNextNode();
+@@ -1568,7 +1568,7 @@
+ unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
+ ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
+ AllocaInst *VarArgShadow =
+- new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
++ new AllocaInst(VarArgArrayTy, "", &DFSF.F->getEntryBlock().front());
+ Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
+ for (unsigned n = 0; i != e; ++i, ++n) {
+ IRB.CreateStore(DFSF.getShadow(*i),
+--- lib/Transforms/Instrumentation/GCOVProfiling.cpp 2015-05-04 12:18:18.000000000 -0700
++++ lib/Transforms/Instrumentation/GCOVProfiling.cpp 2016-01-23 20:38:11.000000000 -0800
+@@ -44,8 +44,10 @@
+
+ #define DEBUG_TYPE "insert-gcov-profiling"
+
++static std::string VersionInitString("402*");
+ static cl::opt<std::string>
+-DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
++DefaultGCOVVersion("default-gcov-version",
++ cl::init(VersionInitString), cl::Hidden,
+ cl::ValueRequired);
+ static cl::opt<bool> DefaultExitBlockBeforeBody("gcov-exit-block-before-body",
+ cl::init(false), cl::Hidden);
+@@ -351,8 +353,8 @@
+ std::string EdgeDestinations;
+ raw_string_ostream EDOS(EdgeDestinations);
+ Function *F = Blocks.begin()->first->getParent();
+- for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
+- GCOVBlock &Block = getBlock(I);
++ for (BasicBlock &I : *F) {
++ GCOVBlock &Block = getBlock(&I);
+ for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
+ EDOS << Block.OutEdges[i]->Number;
+ }
+@@ -393,8 +395,8 @@
+ // Emit edges between blocks.
+ if (Blocks.empty()) return;
+ Function *F = Blocks.begin()->first->getParent();
+- for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
+- GCOVBlock &Block = getBlock(I);
++ for (BasicBlock &I : *F) {
++ GCOVBlock &Block = getBlock(&I);
+ if (Block.OutEdges.empty()) continue;
+
+ writeBytes(EdgeTag, 4);
+@@ -409,8 +411,8 @@
+ }
+
+ // Emit lines for each block.
+- for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
+- getBlock(I).writeOut();
++ for (BasicBlock &I : *F) {
++ getBlock(&I).writeOut();
+ }
+ }
+
+@@ -522,7 +524,7 @@
+ GCOVFunction &Func = *Funcs.back();
+
+ for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
+- GCOVBlock &Block = Func.getBlock(BB);
++ GCOVBlock &Block = Func.getBlock(&*BB);
+ TerminatorInst *TI = BB->getTerminator();
+ if (int successors = TI->getNumSuccessors()) {
+ for (int i = 0; i != successors; ++i) {
+@@ -618,7 +620,7 @@
+ int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
+ if (Successors) {
+ if (Successors == 1) {
+- IRBuilder<> Builder(BB->getFirstInsertionPt());
++ IRBuilder<> Builder(&*BB->getFirstInsertionPt());
+ Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
+ Edge);
+ Value *Count = Builder.CreateLoad(Counter);
+@@ -637,7 +639,7 @@
+ Count = Builder.CreateAdd(Count, Builder.getInt64(1));
+ Builder.CreateStore(Count, Counter);
+ } else {
+- ComplexEdgePreds.insert(BB);
++ ComplexEdgePreds.insert(&*BB);
+ for (int i = 0; i != Successors; ++i)
+ ComplexEdgeSuccs.insert(TI->getSuccessor(i));
+ }
+@@ -653,13 +655,13 @@
+ GlobalVariable *EdgeState = getEdgeStateValue();
+
+ for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
+- IRBuilder<> Builder(ComplexEdgePreds[i + 1]->getFirstInsertionPt());
++ IRBuilder<> Builder(&*ComplexEdgePreds[i + 1]->getFirstInsertionPt());
+ Builder.CreateStore(Builder.getInt32(i), EdgeState);
+ }
+
+ for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
+ // Call runtime to perform increment.
+- IRBuilder<> Builder(ComplexEdgeSuccs[i+1]->getFirstInsertionPt());
++ IRBuilder<> Builder(&*ComplexEdgeSuccs[i + 1]->getFirstInsertionPt());
+ Value *CounterPtrArray =
+ Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
+ i * ComplexEdgePreds.size());
+@@ -743,8 +745,8 @@
+ IRBuilder<> Builder(Succ);
+ Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
+ Edge + i);
+- EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
+- (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
++ EdgeTable[((Succs.idFor(Succ) - 1) * Preds.size()) +
++ (Preds.idFor(&*BB) - 1)] = cast<Constant>(Counter);
+ }
+ }
+ Edge += Successors;
+@@ -913,7 +915,7 @@
+
+ // uint32_t pred = *predecessor;
+ // if (pred == 0xffffffff) return;
+- Argument *Arg = Fn->arg_begin();
++ Argument *Arg = &*Fn->arg_begin();
+ Arg->setName("predecessor");
+ Value *Pred = Builder.CreateLoad(Arg, "pred");
+ Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
+@@ -924,7 +926,7 @@
+ // uint64_t *counter = counters[pred];
+ // if (!counter) return;
+ Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
+- Arg = std::next(Fn->arg_begin());
++ Arg = &*std::next(Fn->arg_begin());
+ Arg->setName("counters");
+ Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
+ Value *Counter = Builder.CreateLoad(GEP, "counter");
+--- lib/Transforms/Instrumentation/InstrProfiling.cpp 2015-02-10 20:41:09.000000000 -0800
++++ lib/Transforms/Instrumentation/InstrProfiling.cpp 2015-11-30 19:51:07.408467787 -0800
+@@ -143,7 +143,7 @@
+ void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
+ GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
+
+- IRBuilder<> Builder(Inc->getParent(), *Inc);
++ IRBuilder<> Builder(Inc);
+ uint64_t Index = Inc->getIndex()->getZExtValue();
+ llvm::Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
+ llvm::Value *Count = Builder.CreateLoad(Addr, "pgocount");
+--- lib/Transforms/Instrumentation/MemorySanitizer.cpp 2015-02-06 14:06:43.000000000 -0800
++++ lib/Transforms/Instrumentation/MemorySanitizer.cpp 2015-11-30 19:55:19.370562015 -0800
+@@ -603,7 +603,7 @@
+ Value *Cmp = IRB.CreateICmpNE(
+ ConvertedShadow, getCleanShadow(ConvertedShadow), "_mscmp");
+ Instruction *CheckTerm = SplitBlockAndInsertIfThen(
+- Cmp, IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
++ Cmp, &*IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
+ IRBuilder<> IRBNew(CheckTerm);
+ IRBNew.CreateAlignedStore(updateOrigin(Origin, IRBNew),
+ getOriginPtr(Addr, IRBNew, Alignment),
+@@ -2396,9 +2396,10 @@
+ // Until we have full dynamic coverage, make sure the retval shadow is 0.
+ Value *Base = getShadowPtrForRetval(&I, IRBBefore);
+ IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
+- Instruction *NextInsn = nullptr;
++ BasicBlock::iterator NextInsn;
+ if (CS.isCall()) {
+- NextInsn = I.getNextNode();
++ NextInsn = ++I.getIterator();
++ assert(NextInsn != I.getParent()->end());
+ } else {
+ BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
+ if (!NormalDest->getSinglePredecessor()) {
+@@ -2410,10 +2411,10 @@
+ return;
+ }
+ NextInsn = NormalDest->getFirstInsertionPt();
+- assert(NextInsn &&
++ assert(NextInsn != NormalDest->end() &&
+ "Could not find insertion point for retval shadow load");
+ }
+- IRBuilder<> IRBAfter(NextInsn);
++ IRBuilder<> IRBAfter(&*NextInsn);
+ Value *RetvalShadow =
+ IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
+ kShadowTLSAlignment, "_msret");
+--- lib/Transforms/Instrumentation/SanitizerCoverage.cpp 2015-01-02 16:54:43.000000000 -0800
++++ lib/Transforms/Instrumentation/SanitizerCoverage.cpp 2015-11-30 19:58:56.426390313 -0800
+@@ -275,7 +275,8 @@
+ bool IsEntryBB = &BB == &F.getEntryBlock();
+ DebugLoc EntryLoc =
+ IsEntryBB ? IP->getDebugLoc().getFnDebugLoc(*C) : IP->getDebugLoc();
+- IRBuilder<> IRB(IP);
++
++ IRBuilder<> IRB(&*IP);
+ IRB.SetCurrentDebugLocation(EntryLoc);
+ SmallVector<Value *, 1> Indices;
+ Value *GuardP = IRB.CreateAdd(
+@@ -290,7 +291,7 @@
+ MDNode::get(*C, None));
+ Value *Cmp = IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
+ Instruction *Ins = SplitBlockAndInsertIfThen(
+- Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
++ Cmp, &*IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
+ IRB.SetInsertPoint(Ins);
+ IRB.SetCurrentDebugLocation(EntryLoc);
+ // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
+@@ -300,7 +301,7 @@
+ if (ClExperimentalTracing) {
+ // Experimental support for tracing.
+ // Insert a callback with the same guard variable as used for coverage.
+- IRB.SetInsertPoint(IP);
++ IRB.SetInsertPoint(&*IP);
+ IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
+ }
+ }
+--- lib/Transforms/ObjCARC/DependencyAnalysis.cpp 2014-11-18 23:49:26.000000000 -0800
++++ lib/Transforms/ObjCARC/DependencyAnalysis.cpp 2015-11-30 20:05:22.864307715 -0800
+@@ -209,7 +209,7 @@
+ SmallPtrSetImpl<Instruction *> &DependingInsts,
+ SmallPtrSetImpl<const BasicBlock *> &Visited,
+ ProvenanceAnalysis &PA) {
+- BasicBlock::iterator StartPos = StartInst;
++ BasicBlock::iterator StartPos = StartInst->getIterator();
+
+ SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
+ Worklist.push_back(std::make_pair(StartBB, StartPos));
+@@ -235,7 +235,7 @@
+ break;
+ }
+
+- Instruction *Inst = --LocalStartPos;
++ Instruction *Inst = &*--LocalStartPos;
+ if (Depends(Flavor, Inst, Arg, PA)) {
+ DependingInsts.insert(Inst);
+ break;
+--- lib/Transforms/ObjCARC/ObjCARCAPElim.cpp 2014-05-16 13:39:27.000000000 -0700
++++ lib/Transforms/ObjCARC/ObjCARCAPElim.cpp 2015-11-30 20:09:20.487861680 -0800
+@@ -72,12 +72,9 @@
+ if (const Function *Callee = CS.getCalledFunction()) {
+ if (Callee->isDeclaration() || Callee->mayBeOverridden())
+ return true;
+- for (Function::const_iterator I = Callee->begin(), E = Callee->end();
+- I != E; ++I) {
+- const BasicBlock *BB = I;
+- for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
+- J != F; ++J)
+- if (ImmutableCallSite JCS = ImmutableCallSite(J))
++ for (const BasicBlock &BB : *Callee) {
++ for (const Instruction &I : BB)
++ if (ImmutableCallSite JCS = ImmutableCallSite(&I))
+ // This recursion depth limit is arbitrary. It's just great
+ // enough to cover known interesting testcases.
+ if (Depth < 3 &&
+@@ -96,7 +93,7 @@
+
+ Instruction *Push = nullptr;
+ for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
+- Instruction *Inst = I++;
++ Instruction *Inst = &*I++;
+ switch (GetBasicInstructionClass(Inst)) {
+ case IC_AutoreleasepoolPush:
+ Push = Inst;
+@@ -169,7 +166,7 @@
+ if (std::next(F->begin()) != F->end())
+ continue;
+ // Ok, a single-block constructor function definition. Try to optimize it.
+- Changed |= OptimizeBB(F->begin());
++ Changed |= OptimizeBB(&F->front());
+ }
+
+ return Changed;
+--- lib/Transforms/ObjCARC/ObjCARCContract.cpp 2014-11-11 13:30:22.000000000 -0800
++++ lib/Transforms/ObjCARC/ObjCARCContract.cpp 2015-12-01 09:48:41.817465473 -0800
+@@ -123,9 +123,10 @@
+ return false;
+
+ // Check that the call is next to the retain.
+- BasicBlock::const_iterator I = Call;
++ BasicBlock::const_iterator I = ++Call->getIterator();
++ while (IsNoopInstruction(&*I))
+ ++I;
+- while (IsNoopInstruction(I)) ++I;
++
+ if (&*I != Retain)
+ return false;
+
+@@ -202,69 +203,166 @@
+ return true;
+ }
+
+-/// Attempt to merge an objc_release with a store, load, and objc_retain to form
+-/// an objc_storeStrong. This can be a little tricky because the instructions
+-/// don't always appear in order, and there may be unrelated intervening
+-/// instructions.
+-void ObjCARCContract::ContractRelease(Instruction *Release,
+- inst_iterator &Iter) {
+- LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
+- if (!Load || !Load->isSimple()) return;
+-
+- // For now, require everything to be in one basic block.
+- BasicBlock *BB = Release->getParent();
+- if (Load->getParent() != BB) return;
+
+- // Walk down to find the store and the release, which may be in either order.
+- BasicBlock::iterator I = Load, End = BB->end();
+- ++I;
+- AliasAnalysis::Location Loc = AA->getLocation(Load);
++static StoreInst* findSafeStoreForStoreStrongContraction(LoadInst *Load,
++ Instruction *Release,
++ ProvenanceAnalysis &PA,
++ AliasAnalysis *AA) {
+ StoreInst *Store = nullptr;
+ bool SawRelease = false;
+- for (; !Store || !SawRelease; ++I) {
+- if (I == End)
+- return;
+
+- Instruction *Inst = I;
++ // Get the location associated with Load.
++ AliasAnalysis::Location Loc = AA->getLocation(Load);
++
++ // Walk down to find the store and the release, which may be in either order.
++ for (auto I = std::next(BasicBlock::iterator(Load)),
++ E = Load->getParent()->end();
++ I != E; ++I) {
++ // If we found the store we were looking for and saw the release,
++ // break. There is no more work to be done.
++ if (Store && SawRelease)
++ break;
++
++ // Now we know that we have not seen either the store or the release. If I
++ // is the release, mark that we saw the release and continue.
++ Instruction *Inst = &*I;
+ if (Inst == Release) {
+ SawRelease = true;
+ continue;
+ }
+
+- InstructionClass Class = GetBasicInstructionClass(Inst);
+-
+- // Unrelated retains are harmless.
+- if (IsRetain(Class))
++ // Otherwise, we check if Inst is a "good" store. Grab the instruction class
++ // of Inst.
++ InstructionClass IC = GetBasicInstructionClass(Inst);
++
++ // If Inst is an unrelated retain, we don't care about it.
++ //
++ // TODO: This is one area where the optimization could be made more
++ // aggressive.
++ if (IsRetain(IC))
+ continue;
+
++ // If we have seen the store, but not the release...
+ if (Store) {
+- // The store is the point where we're going to put the objc_storeStrong,
+- // so make sure there are no uses after it.
+- if (CanUse(Inst, Load, PA, Class))
+- return;
+- } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
+- // We are moving the load down to the store, so check for anything
+- // else which writes to the memory between the load and the store.
+- Store = dyn_cast<StoreInst>(Inst);
+- if (!Store || !Store->isSimple()) return;
+- if (Store->getPointerOperand() != Loc.Ptr) return;
++ // We need to make sure that it is safe to move the release from its
++ // current position to the store. This implies proving that any
++ // instruction in between Store and the Release conservatively can not use
++ // the RCIdentityRoot of Release. If we can prove we can ignore Inst, so
++ // continue...
++ if (!CanUse(Inst, Load, PA, IC)) {
++ continue;
++ }
++
++ // Otherwise, be conservative and return nullptr.
++ return nullptr;
+ }
++
++ // Ok, now we know we have not seen a store yet. See if Inst can write to
++ // our load location, if it can not, just ignore the instruction.
++ if (!(AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod))
++ continue;
++
++ Store = dyn_cast<StoreInst>(Inst);
++
++ // If Inst can, then check if Inst is a simple store. If Inst is not a
++ // store or a store that is not simple, then we have some we do not
++ // understand writing to this memory implying we can not move the load
++ // over the write to any subsequent store that we may find.
++ if (!Store || !Store->isSimple())
++ return nullptr;
++
++ // Then make sure that the pointer we are storing to is Ptr. If so, we
++ // found our Store!
++ if (Store->getPointerOperand() == Loc.Ptr)
++ continue;
++
++ // Otherwise, we have an unknown store to some other ptr that clobbers
++ // Loc.Ptr. Bail!
++ return nullptr;
+ }
+
+- Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
++ // If we did not find the store or did not see the release, fail.
++ if (!Store || !SawRelease)
++ return nullptr;
++
++ // We succeeded!
++ return Store;
++}
++
++static Instruction*
++findRetainForStoreStrongContraction(Value *New, StoreInst *Store,
++ Instruction *Release,
++ ProvenanceAnalysis &PA) {
++ // Walk up from the Store to find the retain.
++ BasicBlock::iterator I = Store->getIterator();
++ BasicBlock::iterator Begin = Store->getParent()->begin();
++ while ((I != Begin) && (GetBasicInstructionClass(&*I) != IC_Retain)) {
++ Instruction *Inst = &*I;
++
++ // This is not exactly correct, but it's non-portable to 3.6.2.
++ if (Inst != Release)
++ return nullptr;
+
+- // Walk up to find the retain.
+- I = Store;
+- BasicBlock::iterator Begin = BB->begin();
+- while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
+ --I;
+- Instruction *Retain = I;
+- if (GetBasicInstructionClass(Retain) != IC_Retain) return;
+- if (GetObjCArg(Retain) != New) return;
++ }
++
++ Instruction *Retain = &*I;
++ if (GetBasicInstructionClass(Retain) != IC_Retain)
++ return nullptr;
++
++ if (GetObjCArg(Retain) != New)
++ return nullptr;
++
++ return Retain;
++}
++
++/// Attempt to merge an objc_release with a store, load, and objc_retain to form
++/// an objc_storeStrong. This can be a little tricky because the instructions
++/// don't always appear in order, and there may be unrelated intervening
++/// instructions.
++void ObjCARCContract::ContractRelease(Instruction *Release,
++ inst_iterator &Iter) {
++ // See if we are releasing something that we just loaded.
++ auto *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
++ if (!Load || !Load->isSimple())
++ return;
++
++ // For now, require everything to be in one basic block.
++ BasicBlock *BB = Release->getParent();
++ if (Load->getParent() != BB)
++ return;
++
++ // First scan down the BB from Load, looking for a store of the RCIdentityRoot
++ // of Load's
++ StoreInst *Store =
++ findSafeStoreForStoreStrongContraction(Load, Release, PA, AA);
++ // If we fail, bail.
++ if (!Store)
++ return;
++
++ // Then find what new_value's RCIdentity Root is.
++ Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
++
++ // Then walk up the BB and look for a retain on New without any intervening
++ // instructions which conservatively might decrement ref counts.
++ Instruction *Retain =
++ findRetainForStoreStrongContraction(New, Store, Release, PA);
++
++ // If we fail, bail.
++ if (!Retain)
++ return;
+
+ Changed = true;
+ ++NumStoreStrongs;
+
++ DEBUG(
++ llvm::dbgs() << " Contracting retain, release into objc_storeStrong.\n"
++ << " Old:\n"
++ << " Store: " << *Store << "\n"
++ << " Release: " << *Release << "\n"
++ << " Retain: " << *Retain << "\n"
++ << " Load: " << *Load << "\n");
++
+ LLVMContext &C = Release->getContext();
+ Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
+ Type *I8XX = PointerType::getUnqual(I8X);
+@@ -274,6 +372,7 @@
+ Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
+ if (Args[1]->getType() != I8X)
+ Args[1] = new BitCastInst(Args[1], I8X, "", Store);
++
+ Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_StoreStrong);
+ CallInst *StoreStrong = CallInst::Create(Decl, Args, "", Store);
+ StoreStrong->setDoesNotThrow();
+@@ -284,7 +383,11 @@
+ // we can set the tail flag once we know it's safe.
+ StoreStrongCalls.insert(StoreStrong);
+
+- if (&*Iter == Store) ++Iter;
++ DEBUG(llvm::dbgs() << " New Store Strong: " << *StoreStrong << "\n");
++
++ if (&*Iter == Store)
++ ++Iter;
++
+ Store->eraseFromParent();
+ Release->eraseFromParent();
+ EraseInstruction(Retain);
+@@ -371,7 +474,8 @@
+ // insert it now.
+ if (!RetainRVMarker)
+ break;
+- BasicBlock::iterator BBI = Inst;
++
++ BasicBlock::iterator BBI = Inst->getIterator();
+ BasicBlock *InstParent = Inst->getParent();
+
+ // Step up to see if the call immediately precedes the RetainRV call.
+@@ -382,11 +486,11 @@
+ BasicBlock *Pred = InstParent->getSinglePredecessor();
+ if (!Pred)
+ goto decline_rv_optimization;
+- BBI = Pred->getTerminator();
++ BBI = Pred->getTerminator()->getIterator();
+ break;
+ }
+ --BBI;
+- } while (IsNoopInstruction(BBI));
++ } while (IsNoopInstruction(&*BBI));
+
+ if (&*BBI == GetObjCArg(Inst)) {
+ DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for "
+--- lib/Transforms/ObjCARC/ObjCARCOpts.cpp 2014-12-09 10:38:53.000000000 -0800
++++ lib/Transforms/ObjCARC/ObjCARCOpts.cpp 2016-01-23 21:53:49.000000000 -0800
+@@ -798,19 +798,22 @@
+
+ /// Enable/disable ARC sequence annotations.
+ static cl::opt<bool>
+-EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
++EnableARCAnnotations("enable-objc-arc-annotations",
+ cl::desc("Enable emission of arc data flow analysis "
+- "annotations"));
++ "annotations"),
++ cl::init(false));
+ static cl::opt<bool>
+-DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
++DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards",
+ cl::desc("Disable check for cfg hazards when "
+- "annotating"));
++ "annotating"),
++ cl::init(false));
++static std::string EmptyInitString("");
+ static cl::opt<std::string>
+ ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
+- cl::init(""),
+ cl::desc("filter out all data flow annotations "
+ "but those that apply to the given "
+- "target llvm identifier."));
++ "target llvm identifier."),
++ cl::init(EmptyInitString));
+
+ /// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
+ /// instruction so that we can track backwards when post processing via the llvm
+@@ -1195,16 +1198,17 @@
+ ImmutableCallSite CS(Arg);
+ if (const Instruction *Call = CS.getInstruction()) {
+ if (Call->getParent() == RetainRV->getParent()) {
+- BasicBlock::const_iterator I = Call;
++ BasicBlock::const_iterator I(Call);
+ ++I;
+- while (IsNoopInstruction(I)) ++I;
++ while (IsNoopInstruction(&*I)) ++I;
+ if (&*I == RetainRV)
+ return false;
+ } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
+ BasicBlock *RetainRVParent = RetainRV->getParent();
+ if (II->getNormalDest() == RetainRVParent) {
+ BasicBlock::const_iterator I = RetainRVParent->begin();
+- while (IsNoopInstruction(I)) ++I;
++ while (IsNoopInstruction(&*I))
++ ++I;
+ if (&*I == RetainRV)
+ return false;
+ }
+@@ -1213,18 +1217,21 @@
+
+ // Check for being preceded by an objc_autoreleaseReturnValue on the same
+ // pointer. In this case, we can delete the pair.
+- BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
++ BasicBlock::iterator I = RetainRV->getIterator(),
++ Begin = RetainRV->getParent()->begin();
+ if (I != Begin) {
+- do --I; while (I != Begin && IsNoopInstruction(I));
+- if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
+- GetObjCArg(I) == Arg) {
++ do
++ --I;
++ while (I != Begin && IsNoopInstruction(&*I));
++ if (GetBasicInstructionClass(&*I) == IC_AutoreleaseRV &&
++ GetObjCArg(&*I) == Arg) {
+ Changed = true;
+ ++NumPeeps;
+
+ DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
+ << "Erasing " << *RetainRV << "\n");
+
+- EraseInstruction(I);
++ EraseInstruction(&*I);
+ EraseInstruction(RetainRV);
+ return true;
+ }
+@@ -1861,9 +1868,9 @@
+ // one of its successor blocks, since we can't insert code after it
+ // in its own block, and we don't want to split critical edges.
+ if (isa<InvokeInst>(Inst))
+- S.InsertReverseInsertPt(BB->getFirstInsertionPt());
++ S.InsertReverseInsertPt(&*BB->getFirstInsertionPt());
+ else
+- S.InsertReverseInsertPt(std::next(BasicBlock::iterator(Inst)));
++ S.InsertReverseInsertPt(&*++Inst->getIterator());
+ S.SetSeq(S_Use);
+ ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
+ } else if (Seq == S_Release && IsUser(Class)) {
+@@ -1875,9 +1882,9 @@
+ assert(!S.HasReverseInsertPts());
+ // As above; handle invoke specially.
+ if (isa<InvokeInst>(Inst))
+- S.InsertReverseInsertPt(BB->getFirstInsertionPt());
++ S.InsertReverseInsertPt(&*BB->getFirstInsertionPt());
+ else
+- S.InsertReverseInsertPt(std::next(BasicBlock::iterator(Inst)));
++ S.InsertReverseInsertPt(&*++Inst->getIterator());
+ }
+ break;
+ case S_Stop:
+@@ -1934,7 +1941,7 @@
+
+ // Visit all the instructions, bottom-up.
+ for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
+- Instruction *Inst = std::prev(I);
++ Instruction *Inst = &*std::prev(I);
+
+ // Invoke instructions are visited as part of their successors (below).
+ if (isa<InvokeInst>(Inst))
+@@ -2144,7 +2151,7 @@
+
+ // Visit all the instructions, top-down.
+ for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
+- Instruction *Inst = I;
++ Instruction *Inst = &*I;
+
+ DEBUG(dbgs() << "Visiting " << *Inst << "\n");
+
+@@ -2219,7 +2226,7 @@
+ // as exits due to ignored edges.
+ SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
+ for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
+- BasicBlock *ExitBB = I;
++ BasicBlock *ExitBB = &*I;
+ BBState &MyStates = BBStates[ExitBB];
+ if (!MyStates.isExit())
+ continue;
+@@ -2655,7 +2662,7 @@
+ // analysis too, but that would want caching. A better approach would be to
+ // use the technique that EarlyCSE uses.
+ inst_iterator Current = std::prev(I);
+- BasicBlock *CurrentBB = Current.getBasicBlockIterator();
++ BasicBlock *CurrentBB = &*Current.getBasicBlockIterator();
+ for (BasicBlock::iterator B = CurrentBB->begin(),
+ J = Current.getInstructionIterator();
+ J != B; --J) {
+@@ -2910,9 +2917,8 @@
+
+ SmallPtrSet<Instruction *, 4> DependingInstructions;
+ SmallPtrSet<const BasicBlock *, 4> Visited;
+- for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
+- BasicBlock *BB = FI;
+- ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
++ for (BasicBlock &BB: F) {
++ ReturnInst *Ret = dyn_cast<ReturnInst>(&BB.back());
+
+ DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
+
+@@ -2925,7 +2931,7 @@
+ // dependent on Arg such that there are no instructions dependent on Arg
+ // that need a positive ref count in between the autorelease and Ret.
+ CallInst *Autorelease =
+- FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
++ FindPredecessorAutoreleaseWithSafePath(Arg, &BB, Ret,
+ DependingInstructions, Visited,
+ PA);
+ DependingInstructions.clear();
+@@ -2935,7 +2941,7 @@
+ continue;
+
+ CallInst *Retain =
+- FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
++ FindPredecessorRetainWithSafePath(Arg, &BB, Autorelease,
+ DependingInstructions, Visited, PA);
+ DependingInstructions.clear();
+ Visited.clear();
+--- lib/Transforms/ObjCARC/ObjCARCUtil.cpp 2013-07-10 11:49:00.000000000 -0700
++++ lib/Transforms/ObjCARC/ObjCARCUtil.cpp 2015-12-06 09:20:57.733406625 -0800
+@@ -91,7 +91,9 @@
+ .Default(IC_CallOrUser);
+
+ // One argument.
+- const Argument *A0 = AI++;
++ const Argument *A0 = &*AI;
++ ++AI;
++
+ if (AI == AE)
+ // Argument is a pointer.
+ if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
+@@ -127,7 +129,9 @@
+ }
+
+ // Two arguments, first is i8**.
+- const Argument *A1 = AI++;
++ const Argument *A1 = &*AI;
++ ++AI;
++
+ if (AI == AE)
+ if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
+ if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
+--- lib/Transforms/Scalar/ADCE.cpp 2014-11-18 23:49:26.000000000 -0800
++++ lib/Transforms/Scalar/ADCE.cpp 2015-11-28 19:38:59.304881103 -0800
+@@ -63,8 +63,8 @@
+ isa<DbgInfoIntrinsic>(I.getInstructionIterator()) ||
+ isa<LandingPadInst>(I.getInstructionIterator()) ||
+ I->mayHaveSideEffects()) {
+- alive.insert(I.getInstructionIterator());
+- worklist.push_back(I.getInstructionIterator());
++ alive.insert(&*I);
++ worklist.push_back(&*I);
+ }
+
+ // Propagate liveness backwards to operands.
+@@ -82,8 +82,8 @@
+ // value of the function, and may therefore be deleted safely.
+ // NOTE: We reuse the worklist vector here for memory efficiency.
+ for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
+- if (!alive.count(I.getInstructionIterator())) {
+- worklist.push_back(I.getInstructionIterator());
++ if (!alive.count(&*I)) {
++ worklist.push_back(&*I);
+ I->dropAllReferences();
+ }
+
+--- lib/Transforms/Scalar/ConstantHoisting.cpp 2014-10-04 09:55:56.000000000 -0700
++++ lib/Transforms/Scalar/ConstantHoisting.cpp 2015-11-28 19:44:37.366065720 -0800
+@@ -361,9 +361,9 @@
+ /// into an instruction itself.
+ void ConstantHoisting::collectConstantCandidates(Function &Fn) {
+ ConstCandMapType ConstCandMap;
+- for (Function::iterator BB : Fn)
+- for (BasicBlock::iterator Inst : *BB)
+- collectConstantCandidates(ConstCandMap, Inst);
++ for (BasicBlock &BB : Fn)
++ for (Instruction &Inst : BB)
++ collectConstantCandidates(ConstCandMap, &Inst);
+ }
+
+ /// \brief Find the base constant within the given range and rebase all other
+--- lib/Transforms/Scalar/CorrelatedValuePropagation.cpp 2014-09-07 13:29:59.000000000 -0700
++++ lib/Transforms/Scalar/CorrelatedValuePropagation.cpp 2015-11-28 19:45:51.045707253 -0800
+@@ -296,7 +296,8 @@
+ for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
+ bool BBChanged = false;
+ for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
+- Instruction *II = BI++;
++ Instruction *II = &*BI;
++ ++BI;
+ switch (II->getOpcode()) {
+ case Instruction::Select:
+ BBChanged |= processSelect(cast<SelectInst>(II));
+--- lib/Transforms/Scalar/DCE.cpp 2014-04-21 19:55:47.000000000 -0700
++++ lib/Transforms/Scalar/DCE.cpp 2015-11-28 19:46:43.738032658 -0800
+@@ -45,7 +45,8 @@
+ TargetLibraryInfo *TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
+ bool Changed = false;
+ for (BasicBlock::iterator DI = BB.begin(); DI != BB.end(); ) {
+- Instruction *Inst = DI++;
++ Instruction *Inst = &*DI;
++ ++DI;
+ if (isInstructionTriviallyDead(Inst, TLI)) {
+ Inst->eraseFromParent();
+ Changed = true;
+--- lib/Transforms/Scalar/DeadStoreElimination.cpp 2014-10-17 04:56:00.000000000 -0700
++++ lib/Transforms/Scalar/DeadStoreElimination.cpp 2015-11-28 20:06:21.344415630 -0800
+@@ -64,11 +64,11 @@
+ TLI = AA->getTargetLibraryInfo();
+
+ bool Changed = false;
+- for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
++ for (BasicBlock &I : F)
+ // Only check non-dead blocks. Dead blocks may have strange pointer
+ // cycles that will confuse alias analysis.
+- if (DT->isReachableFromEntry(I))
+- Changed |= runOnBasicBlock(*I);
++ if (DT->isReachableFromEntry(&I))
++ Changed |= runOnBasicBlock(I);
+
+ AA = nullptr; MD = nullptr; DT = nullptr;
+ return Changed;
+@@ -488,7 +488,8 @@
+
+ // Do a top-down walk on the BB.
+ for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
+- Instruction *Inst = BBI++;
++ Instruction *Inst = &*BBI;
++ ++BBI;
+
+ // Handle 'free' calls specially.
+ if (CallInst *F = isFreeCall(Inst, TLI)) {
+@@ -518,7 +519,7 @@
+
+ // DeleteDeadInstruction can delete the current instruction. Save BBI
+ // in case we need it.
+- WeakVH NextInst(BBI);
++ WeakVH NextInst(&*BBI);
+
+ DeleteDeadInstruction(SI, *MD, TLI);
+
+@@ -573,7 +574,7 @@
+
+ // DeleteDeadInstruction can delete the current instruction in loop
+ // cases, reset BBI.
+- BBI = Inst;
++ BBI = Inst->getIterator();
+ if (BBI != BB.begin())
+ --BBI;
+ break;
+@@ -619,7 +620,8 @@
+ if (AA->getModRefInfo(DepWrite, Loc) & AliasAnalysis::Ref)
+ break;
+
+- InstDep = MD->getPointerDependencyFrom(Loc, false, DepWrite, &BB);
++ InstDep = MD->getPointerDependencyFrom(Loc, false,
++ DepWrite->getIterator(), &BB);
+ }
+ }
+
+@@ -661,7 +663,8 @@
+ Instruction *InstPt = BB->getTerminator();
+ if (BB == F->getParent()) InstPt = F;
+
+- MemDepResult Dep = MD->getPointerDependencyFrom(Loc, false, InstPt, BB);
++ MemDepResult Dep = MD->getPointerDependencyFrom(Loc, false,
++ InstPt->getIterator(), BB);
+ while (Dep.isDef() || Dep.isClobber()) {
+ Instruction *Dependency = Dep.getInst();
+ if (!hasMemoryWrite(Dependency, TLI) || !isRemovable(Dependency))
+@@ -674,7 +677,7 @@
+ if (!AA->isMustAlias(F->getArgOperand(0), DepPointer))
+ break;
+
+- Instruction *Next = std::next(BasicBlock::iterator(Dependency));
++ Instruction *Next = &*std::next(BasicBlock::iterator(Dependency));
+
+ // DCE instructions only used to calculate that store
+ DeleteDeadInstruction(Dependency, *MD, TLI);
+@@ -686,7 +689,7 @@
+ // s[0] = 0;
+ // s[1] = 0; // This has just been deleted.
+ // free(s);
+- Dep = MD->getPointerDependencyFrom(Loc, false, Next, BB);
++ Dep = MD->getPointerDependencyFrom(Loc, false, Next->getIterator(), BB);
+ }
+
+ if (Dep.isNonLocal())
+@@ -710,33 +713,32 @@
+ SmallSetVector<Value*, 16> DeadStackObjects;
+
+ // Find all of the alloca'd pointers in the entry block.
+- BasicBlock *Entry = BB.getParent()->begin();
+- for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I) {
+- if (isa<AllocaInst>(I))
+- DeadStackObjects.insert(I);
++ BasicBlock &Entry = BB.getParent()->front();
++ for (Instruction &I : Entry) {
++ if (isa<AllocaInst>(&I))
++ DeadStackObjects.insert(&I);
+
+ // Okay, so these are dead heap objects, but if the pointer never escapes
+ // then it's leaked by this function anyways.
+- else if (isAllocLikeFn(I, TLI) && !PointerMayBeCaptured(I, true, true))
+- DeadStackObjects.insert(I);
++ else if (isAllocLikeFn(&I, TLI) && !PointerMayBeCaptured(&I, true, true))
++ DeadStackObjects.insert(&I);
+ }
+
+ // Treat byval or inalloca arguments the same, stores to them are dead at the
+ // end of the function.
+- for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
+- AE = BB.getParent()->arg_end(); AI != AE; ++AI)
+- if (AI->hasByValOrInAllocaAttr())
+- DeadStackObjects.insert(AI);
++ for (Argument &AI : BB.getParent()->args())
++ if (AI.hasByValOrInAllocaAttr())
++ DeadStackObjects.insert(&AI);
+
+ // Scan the basic block backwards
+ for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
+ --BBI;
+
+ // If we find a store, check to see if it points into a dead stack value.
+- if (hasMemoryWrite(BBI, TLI) && isRemovable(BBI)) {
++ if (hasMemoryWrite(&*BBI, TLI) && isRemovable(&*BBI)) {
+ // See through pointer-to-pointer bitcasts
+ SmallVector<Value *, 4> Pointers;
+- GetUnderlyingObjects(getStoredPointerOperand(BBI), Pointers);
++ GetUnderlyingObjects(getStoredPointerOperand(&*BBI), Pointers);
+
+ // Stores to stack values are valid candidates for removal.
+ bool AllDead = true;
+@@ -748,7 +750,8 @@
+ }
+
+ if (AllDead) {
+- Instruction *Dead = BBI++;
++ Instruction *Dead = &*BBI;
++ ++BBI;
+
+ DEBUG(dbgs() << "DSE: Dead Store at End of Block:\n DEAD: "
+ << *Dead << "\n Objects: ";
+@@ -769,8 +772,9 @@
+ }
+
+ // Remove any dead non-memory-mutating instructions.
+- if (isInstructionTriviallyDead(BBI, TLI)) {
+- Instruction *Inst = BBI++;
++ if (isInstructionTriviallyDead(&*BBI, TLI)) {
++ Instruction *Inst = &*BBI;
++ ++BBI;
+ DeleteDeadInstruction(Inst, *MD, TLI, &DeadStackObjects);
+ ++NumFastOther;
+ MadeChange = true;
+@@ -780,15 +784,15 @@
+ if (isa<AllocaInst>(BBI)) {
+ // Remove allocas from the list of dead stack objects; there can't be
+ // any references before the definition.
+- DeadStackObjects.remove(BBI);
++ DeadStackObjects.remove(&*BBI);
+ continue;
+ }
+
+ if (CallSite CS = cast<Value>(BBI)) {
+ // Remove allocation function calls from the list of dead stack objects;
+ // there can't be any references before the definition.
+- if (isAllocLikeFn(BBI, TLI))
+- DeadStackObjects.remove(BBI);
++ if (isAllocLikeFn(&*BBI, TLI))
++ DeadStackObjects.remove(&*BBI);
+
+ // If this call does not access memory, it can't be loading any of our
+ // pointers.
+--- lib/Transforms/Scalar/EarlyCSE.cpp 2015-02-10 18:23:00.000000000 -0800
++++ lib/Transforms/Scalar/EarlyCSE.cpp 2015-11-28 20:08:04.692689072 -0800
+@@ -427,7 +427,8 @@
+ // See if any instructions in the block can be eliminated. If so, do it. If
+ // not, add them to AvailableValues.
+ for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
+- Instruction *Inst = I++;
++ Instruction *Inst = &*I;
++ ++I;
+
+ // Dead instructions should just be removed.
+ if (isInstructionTriviallyDead(Inst, TLI)) {
+--- lib/Transforms/Scalar/FlattenCFGPass.cpp 2014-04-21 19:55:47.000000000 -0700
++++ lib/Transforms/Scalar/FlattenCFGPass.cpp 2015-11-28 20:09:20.884486852 -0800
+@@ -59,7 +59,7 @@
+ // Loop over all of the basic blocks and remove them if they are unneeded...
+ //
+ for (Function::iterator BBIt = F.begin(); BBIt != F.end();) {
+- if (FlattenCFG(BBIt++, AA)) {
++ if (FlattenCFG(&*BBIt++, AA)) {
+ LocalChange = true;
+ }
+ }
+--- lib/Transforms/Scalar/GVN.cpp 2015-05-05 07:43:00.000000000 -0700
++++ lib/Transforms/Scalar/GVN.cpp 2015-11-28 20:13:21.312881435 -0800
+@@ -1123,7 +1123,7 @@
+ uint64_t StoreSize = (DL.getTypeSizeInBits(SrcVal->getType()) + 7) / 8;
+ uint64_t LoadSize = (DL.getTypeSizeInBits(LoadTy) + 7) / 8;
+
+- IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
++ IRBuilder<> Builder(InsertPt);
+
+ // Compute which bits of the stored value are being used by the load. Convert
+ // to an integer type to start with.
+@@ -1220,7 +1220,7 @@
+ LLVMContext &Ctx = LoadTy->getContext();
+ uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy)/8;
+
+- IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
++ IRBuilder<> Builder(InsertPt);
+
+ // We know that this method is only called when the mem transfer fully
+ // provides the bits for the load.
+@@ -2372,7 +2372,8 @@
+ // Merge unconditional branches, allowing PRE to catch more
+ // optimization opportunities.
+ for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
+- BasicBlock *BB = FI++;
++ BasicBlock *BB = &*FI;
++ ++FI;
+
+ bool removedBlock = MergeBlockIntoPredecessor(BB, this);
+ if (removedBlock) ++NumGVNBlocks;
+@@ -2425,7 +2426,7 @@
+
+ for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
+ BI != BE;) {
+- ChangedFunction |= processInstruction(BI);
++ ChangedFunction |= processInstruction(&*BI);
+ if (InstrsToErase.empty()) {
+ ++BI;
+ continue;
+@@ -2580,7 +2581,8 @@
+ // Create a PHI to make the value available in this block.
+ PHINode *Phi =
+ PHINode::Create(CurInst->getType(), predMap.size(),
+- CurInst->getName() + ".pre-phi", CurrentBlock->begin());
++ CurInst->getName() + ".pre-phi",
++ &CurrentBlock->front());
+ for (unsigned i = 0, e = predMap.size(); i != e; ++i) {
+ if (Value *V = predMap[i].first)
+ Phi->addIncoming(V, predMap[i].second);
+@@ -2631,7 +2633,8 @@
+ for (BasicBlock::iterator BI = CurrentBlock->begin(),
+ BE = CurrentBlock->end();
+ BI != BE;) {
+- Instruction *CurInst = BI++;
++ Instruction *CurInst = &*BI;
++ ++BI;
+ Changed = performScalarPRE(CurInst);
+ }
+ }
+--- lib/Transforms/Scalar/IndVarSimplify.cpp 2014-11-18 23:49:26.000000000 -0800
++++ lib/Transforms/Scalar/IndVarSimplify.cpp 2015-11-29 07:09:51.854588965 -0800
+@@ -435,7 +435,7 @@
+ // platforms.
+ if (WeakPH) {
+ Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
+- PN->getParent()->getFirstInsertionPt());
++ &*PN->getParent()->getFirstInsertionPt());
+ PN->replaceAllUsesWith(Conv);
+ RecursivelyDeleteTriviallyDeadInstructions(PN, TLI);
+ }
+@@ -998,7 +998,7 @@
+ PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide",
+ UsePhi);
+ WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
+- IRBuilder<> Builder(WidePhi->getParent()->getFirstInsertionPt());
++ IRBuilder<> Builder(&*WidePhi->getParent()->getFirstInsertionPt());
+ Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType());
+ UsePhi->replaceAllUsesWith(Trunc);
+ DeadInsts.push_back(UsePhi);
+@@ -1149,7 +1149,7 @@
+ // either find an existing phi or materialize a new one. Either way, we
+ // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
+ // of the phi-SCC dominates the loop entry.
+- Instruction *InsertPt = L->getHeader()->begin();
++ Instruction *InsertPt = &L->getHeader()->front();
+ WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
+
+ // Remembering the WideIV increment generated by SCEVExpander allows
+@@ -1835,8 +1835,8 @@
+ BasicBlock *Preheader = L->getLoopPreheader();
+ if (!Preheader) return;
+
+- Instruction *InsertPt = ExitBlock->getFirstInsertionPt();
+- BasicBlock::iterator I = Preheader->getTerminator();
++ Instruction *InsertPt = &*ExitBlock->getFirstInsertionPt();
++ BasicBlock::iterator I(Preheader->getTerminator());
+ while (I != Preheader->begin()) {
+ --I;
+ // New instructions were inserted at the end of the preheader.
+@@ -1889,7 +1889,7 @@
+ continue;
+
+ // Otherwise, sink it to the exit block.
+- Instruction *ToMove = I;
++ Instruction *ToMove = &*I;
+ bool Done = false;
+
+ if (I != Preheader->begin()) {
+--- lib/Transforms/Scalar/JumpThreading.cpp 2015-01-12 19:46:47.000000000 -0800
++++ lib/Transforms/Scalar/JumpThreading.cpp 2015-11-29 07:18:33.215512385 -0800
+@@ -179,7 +179,7 @@
+ do {
+ Changed = false;
+ for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
+- BasicBlock *BB = I;
++ BasicBlock *BB = &*I;
+ // Thread all of the branches we can over this block.
+ while (ProcessBlock(BB))
+ Changed = true;
+@@ -242,7 +242,7 @@
+ static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB,
+ unsigned Threshold) {
+ /// Ignore PHI nodes, these will be flattened when duplication happens.
+- BasicBlock::const_iterator I = BB->getFirstNonPHI();
++ BasicBlock::const_iterator I(BB->getFirstNonPHI());
+
+ // FIXME: THREADING will delete values that are just used to compute the
+ // branch, so they shouldn't count against the duplication cost.
+@@ -890,7 +890,7 @@
+
+ // Scan a few instructions up from the load, to see if it is obviously live at
+ // the entry to its block.
+- BasicBlock::iterator BBIt = LI;
++ BasicBlock::iterator BBIt(LI);
+
+ if (Value *AvailableVal =
+ FindAvailableLoadedValue(LoadedPtr, LoadBB, BBIt, 6)) {
+@@ -1019,7 +1019,7 @@
+ // Create a PHI node at the start of the block for the PRE'd load value.
+ pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB);
+ PHINode *PN = PHINode::Create(LI->getType(), std::distance(PB, PE), "",
+- LoadBB->begin());
++ &LoadBB->front());
+ PN->takeName(LI);
+ PN->setDebugLoc(LI->getDebugLoc());
+
+@@ -1449,7 +1449,7 @@
+ Instruction *New = BI->clone();
+ New->setName(BI->getName());
+ NewBB->getInstList().push_back(New);
+- ValueMapping[BI] = New;
++ ValueMapping[&*BI] = New;
+
+ // Remap operands to patch up intra-block references.
+ for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
+@@ -1499,8 +1499,8 @@
+ // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
+ // with the two values we know.
+ SSAUpdate.Initialize(I->getType(), I->getName());
+- SSAUpdate.AddAvailableValue(BB, I);
+- SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
++ SSAUpdate.AddAvailableValue(BB, &*I);
++ SSAUpdate.AddAvailableValue(NewBB, ValueMapping[&*I]);
+
+ while (!UsesToRename.empty())
+ SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
+@@ -1605,12 +1605,12 @@
+ // phi translation.
+ if (Value *IV = SimplifyInstruction(New, DL)) {
+ delete New;
+- ValueMapping[BI] = IV;
++ ValueMapping[&*BI] = IV;
+ } else {
+ // Otherwise, insert the new instruction into the block.
+ New->setName(BI->getName());
+- PredBB->getInstList().insert(OldPredBranch, New);
+- ValueMapping[BI] = New;
++ PredBB->getInstList().insert(OldPredBranch->getIterator(), New);
++ ValueMapping[&*BI] = New;
+ }
+ }
+
+@@ -1652,8 +1652,8 @@
+ // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
+ // with the two values we know.
+ SSAUpdate.Initialize(I->getType(), I->getName());
+- SSAUpdate.AddAvailableValue(BB, I);
+- SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
++ SSAUpdate.AddAvailableValue(BB, &*I);
++ SSAUpdate.AddAvailableValue(PredBB, ValueMapping[&*I]);
+
+ while (!UsesToRename.empty())
+ SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
+--- lib/Transforms/Scalar/LICM.cpp 2014-12-29 15:00:57.000000000 -0800
++++ lib/Transforms/Scalar/LICM.cpp 2015-11-27 19:41:29.442793583 -0800
+@@ -573,7 +573,7 @@
+ if (!OLoop->contains(&PN)) {
+ PHINode *OpPN =
+ PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
+- OInst->getName() + ".lcssa", ExitBlock.begin());
++ OInst->getName() + ".lcssa", &ExitBlock.front());
+ for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
+ OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
+ *OI = OpPN;
+@@ -720,7 +720,7 @@
+ // store that.
+ PHINode *PN = PHINode::Create(
+ I->getType(), PredCache.GetNumPreds(BB),
+- I->getName() + ".lcssa", BB->begin());
++ I->getName() + ".lcssa", &BB->front());
+ for (BasicBlock **PI = PredCache.GetPreds(BB); *PI; ++PI)
+ PN->addIncoming(I, *PI);
+ return PN;
+@@ -916,7 +916,7 @@
+ CurLoop->getUniqueExitBlocks(ExitBlocks);
+ InsertPts.resize(ExitBlocks.size());
+ for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
+- InsertPts[i] = ExitBlocks[i]->getFirstInsertionPt();
++ InsertPts[i] = &*ExitBlocks[i]->getFirstInsertionPt();
+ }
+
+ // We use the SSAUpdater interface to insert phi nodes as required.
+--- lib/Transforms/Scalar/LoopIdiomRecognize.cpp 2014-06-13 20:48:29.000000000 -0700
++++ lib/Transforms/Scalar/LoopIdiomRecognize.cpp 2015-11-29 07:21:21.325412485 -0800
+@@ -441,9 +441,9 @@
+ // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
+ {
+ CountInst = nullptr;
+- for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI(),
++ for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
+ IterE = LoopEntry->end(); Iter != IterE; Iter++) {
+- Instruction *Inst = Iter;
++ Instruction *Inst = &*Iter;
+ if (Inst->getOpcode() != Instruction::Add)
+ continue;
+
+@@ -571,7 +571,7 @@
+ ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
+ Type *Ty = TripCnt->getType();
+
+- PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", Body->begin());
++ PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &(Body->front()));
+
+ Builder.SetInsertPoint(LbCond);
+ Value *Opnd1 = cast<Value>(TcPhi);
+@@ -736,10 +736,12 @@
+
+ bool MadeChange = false;
+ for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
+- Instruction *Inst = I++;
++ Instruction *Inst = &*I;
++ ++I;
++
+ // Look for store instructions, which may be optimized to memset/memcpy.
+ if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
+- WeakVH InstPtr(I);
++ WeakVH InstPtr(&*I);
+ if (!processLoopStore(SI, BECount)) continue;
+ MadeChange = true;
+
+@@ -752,7 +754,7 @@
+
+ // Look for memset instructions, which may be optimized to a larger memset.
+ if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
+- WeakVH InstPtr(I);
++ WeakVH InstPtr(&*I);
+ if (!processLoopMemSet(MSI, BECount)) continue;
+ MadeChange = true;
+
+@@ -891,8 +893,7 @@
+ for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
+ ++BI)
+ for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
+- if (&*I != IgnoredStore &&
+- (AA.getModRefInfo(I, StoreLoc) & Access))
++ if (&*I != IgnoredStore && (AA.getModRefInfo(&*I, StoreLoc) & Access))
+ return true;
+
+ return false;
+--- lib/Transforms/Scalar/LoopInstSimplify.cpp 2015-01-28 09:35:18.000000000 -0800
++++ lib/Transforms/Scalar/LoopInstSimplify.cpp 2015-11-28 15:26:59.128054267 -0800
+@@ -112,7 +112,8 @@
+
+ // Simplify instructions in the current basic block.
+ for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
+- Instruction *I = BI++;
++ Instruction *I = &*BI;
++ BI++;
+
+ // The first time through the loop ToSimplify is empty and we try to
+ // simplify all instructions. On later iterations ToSimplify is not
+--- lib/Transforms/Scalar/LoopRerollPass.cpp 2014-10-28 04:54:52.000000000 -0700
++++ lib/Transforms/Scalar/LoopRerollPass.cpp 2015-11-29 07:34:50.826695128 -0800
+@@ -373,7 +373,7 @@
+ continue;
+
+ if (const SCEVAddRecExpr *PHISCEV =
+- dyn_cast<SCEVAddRecExpr>(SE->getSCEV(I))) {
++ dyn_cast<SCEVAddRecExpr>(SE->getSCEV(&*I))) {
+ if (PHISCEV->getLoop() != L)
+ continue;
+ if (!PHISCEV->isAffine())
+@@ -387,7 +387,7 @@
+
+ DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " <<
+ *PHISCEV << "\n");
+- PossibleIVs.push_back(I);
++ PossibleIVs.push_back(&*I);
+ }
+ }
+ }
+@@ -445,7 +445,7 @@
+ if (!I->getType()->isSingleValueType())
+ continue;
+
+- SimpleLoopReduction SLR(I, L);
++ SimpleLoopReduction SLR(&*I, L);
+ if (!SLR.valid())
+ continue;
+
+@@ -856,35 +856,36 @@
+ continue;
+ if (cast<Instruction>(J1) == IV)
+ continue;
+- if (!BaseUseSet.count(J1))
++ if (!BaseUseSet.count(&*J1))
+ continue;
+- if (PossibleRedPHISet.count(J1)) // Skip reduction PHIs.
++ if (PossibleRedPHISet.count(&*J1)) // Skip reduction PHIs.
+ continue;
+
+- while (J2 != JE && (!RootUseSet.count(J2) ||
++ while (J2 != JE && (!RootUseSet.count(&*J2) ||
+ std::find(Roots[i].begin(), Roots[i].end(), J2) !=
+ Roots[i].end())) {
+ // As we iterate through the instructions, instructions that don't
+ // belong to previous iterations (or the base case), must belong to
+ // future iterations. We want to track the alias set of writes from
+ // previous iterations.
+- if (!isa<PHINode>(J2) && !BaseUseSet.count(J2) &&
+- !AllRootUses.count(J2)) {
++ if (!isa<PHINode>(J2) && !BaseUseSet.count(&*J2) &&
++ !AllRootUses.count(&*J2)) {
+ if (J2->mayWriteToMemory())
+- AST.add(J2);
++ AST.add(&*J2);
+
+ // Note: This is specifically guarded by a check on isa<PHINode>,
+ // which while a valid (somewhat arbitrary) micro-optimization, is
+ // needed because otherwise isSafeToSpeculativelyExecute returns
+ // false on PHI nodes.
+- if (!isSimpleLoadStore(J2) && !isSafeToSpeculativelyExecute(J2, DL))
++ if (!isSimpleLoadStore(&*J2) &&
++ !isSafeToSpeculativelyExecute(&*J2, DL))
+ FutureSideEffects = true;
+ }
+
+ ++J2;
+ }
+
+- if (!J1->isSameOperationAs(J2)) {
++ if (!J1->isSameOperationAs(&*J2)) {
+ DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
+ " vs. " << *J2 << "\n");
+ MatchFailed = true;
+@@ -894,7 +895,7 @@
+ // Make sure that this instruction, which is in the use set of this
+ // root instruction, does not also belong to the base set or the set of
+ // some previous root instruction.
+- if (BaseUseSet.count(J2) || AllRootUses.count(J2)) {
++ if (BaseUseSet.count(&*J2) || AllRootUses.count(&*J2)) {
+ DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
+ " vs. " << *J2 << " (prev. case overlap)\n");
+ MatchFailed = true;
+@@ -907,7 +908,7 @@
+ if (J2->mayReadFromMemory()) {
+ for (AliasSetTracker::iterator K = AST.begin(), KE = AST.end();
+ K != KE && !MatchFailed; ++K) {
+- if (K->aliasesUnknownInst(J2, *AA)) {
++ if (K->aliasesUnknownInst(&*J2, *AA)) {
+ DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
+ " vs. " << *J2 << " (depends on future store)\n");
+ MatchFailed = true;
+@@ -921,10 +922,10 @@
+ // them, and this matching fails. As an exception, we allow the alias
+ // set tracker to handle regular (simple) load/store dependencies.
+ if (FutureSideEffects &&
+- ((!isSimpleLoadStore(J1) &&
+- !isSafeToSpeculativelyExecute(J1, DL)) ||
+- (!isSimpleLoadStore(J2) &&
+- !isSafeToSpeculativelyExecute(J2, DL)))) {
++ ((!isSimpleLoadStore(&*J1) &&
++ !isSafeToSpeculativelyExecute(&*J1, &*DL)) ||
++ (!isSimpleLoadStore(&*J2) &&
++ !isSafeToSpeculativelyExecute(&*J2, &*DL)))) {
+ DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
+ " vs. " << *J2 <<
+ " (side effects prevent reordering)\n");
+@@ -942,7 +943,7 @@
+ // x += a[i]; x += b[i];
+ // x += a[i+1]; x += b[i+1];
+ // x += b[i+2]; x += a[i+2];
+- bool InReduction = Reductions.isPairInSame(J1, J2);
++ bool InReduction = Reductions.isPairInSame(&*J1, &*J2);
+
+ if (!(InReduction && J1->isAssociative())) {
+ bool Swapped = false, SomeOpMatched = false;
+@@ -954,7 +955,7 @@
+ // part of the reduction.
+ if (InReduction)
+ if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
+- if (Reductions.isPairInSame(J2, Op2I))
++ if (Reductions.isPairInSame(&*J2, Op2I))
+ continue;
+
+ DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
+@@ -985,8 +986,8 @@
+ }
+ }
+
+- if ((!PossibleRedLastSet.count(J1) && hasUsesOutsideLoop(J1, L)) ||
+- (!PossibleRedLastSet.count(J2) && hasUsesOutsideLoop(J2, L))) {
++ if ((!PossibleRedLastSet.count(&*J1) && hasUsesOutsideLoop(&*J1, L)) ||
++ (!PossibleRedLastSet.count(&*J2) && hasUsesOutsideLoop(&*J2, L))) {
+ DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
+ " vs. " << *J2 << " (uses outside loop)\n");
+ MatchFailed = true;
+@@ -994,10 +995,10 @@
+ }
+
+ if (!MatchFailed)
+- BaseMap.insert(std::pair<Value *, Value *>(J2, J1));
++ BaseMap.insert(std::pair<Value *, Value *>(&*J2, &*J1));
+
+- AllRootUses.insert(J2);
+- Reductions.recordPair(J1, J2, i+1);
++ AllRootUses.insert(&*J2);
++ Reductions.recordPair(&*J1, &*J2, i+1);
+
+ ++J2;
+ }
+@@ -1025,15 +1026,15 @@
+ continue;
+ if (cast<Instruction>(J) == IV)
+ continue;
+- if (BaseUseSet.count(J) || AllRootUses.count(J) ||
+- (LoopIncUseSet.count(J) && (J->isTerminator() ||
+- isSafeToSpeculativelyExecute(J, DL))))
++ if (BaseUseSet.count(&*J) || AllRootUses.count(&*J) ||
++ (LoopIncUseSet.count(&*J) && (J->isTerminator() ||
++ isSafeToSpeculativelyExecute(&*J, &*DL))))
+ continue;
+
+- if (AllRoots.count(J))
++ if (AllRoots.count(&*J))
+ continue;
+
+- if (Reductions.isSelectedPHI(J))
++ if (Reductions.isSelectedPHI(&*J))
+ continue;
+
+ DEBUG(dbgs() << "LRR: aborting reroll based on " << *RealIV <<
+@@ -1080,7 +1081,7 @@
+ L, SCEV::FlagAnyWrap));
+ { // Limit the lifetime of SCEVExpander.
+ SCEVExpander Expander(*SE, "reroll");
+- Value *NewIV = Expander.expandCodeFor(H, IV->getType(), Header->begin());
++ Value *NewIV = Expander.expandCodeFor(H, IV->getType(), &(Header->front()));
+
+ for (DenseSet<Instruction *>::iterator J = BaseUseSet.begin(),
+ JE = BaseUseSet.end(); J != JE; ++J)
+--- lib/Transforms/Scalar/LoopRotation.cpp 2015-03-09 13:26:36.000000000 -0700
++++ lib/Transforms/Scalar/LoopRotation.cpp 2015-11-29 08:53:24.120179108 -0800
+@@ -141,7 +141,7 @@
+ // as necessary.
+ SSAUpdater SSA;
+ for (I = OrigHeader->begin(); I != E; ++I) {
+- Value *OrigHeaderVal = I;
++ Value *OrigHeaderVal = &*I;
+
+ // If there are no uses of the value (e.g. because it returns void), there
+ // is nothing to rewrite.
+@@ -203,8 +203,7 @@
+ MultiExitLoop = true;
+
+ for (BasicBlock::iterator I = Begin; I != End; ++I) {
+-
+- if (!isSafeToSpeculativelyExecute(I))
++ if (!isSafeToSpeculativelyExecute(&*I))
+ return false;
+
+ if (isa<DbgInfoIntrinsic>(I))
+@@ -287,14 +286,15 @@
+ if (!BI)
+ return false;
+
+- if (!shouldSpeculateInstrs(Latch->begin(), Jmp, L))
++ if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
+ return false;
+
+ DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
+ << LastExit->getName() << "\n");
+
+ // Hoist the instructions from Latch into LastExit.
+- LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
++ LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(),
++ Latch->begin(), Jmp->getIterator());
+
+ unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
+ BasicBlock *Header = Jmp->getSuccessor(0);
+@@ -416,7 +416,8 @@
+ // possible or create a clone in the OldPreHeader if not.
+ TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
+ while (I != E) {
+- Instruction *Inst = I++;
++ Instruction *Inst = &*I;
++ ++I;
+
+ // If the instruction's operands are invariant and it doesn't read or write
+ // memory, then it is safe to hoist. Doing this doesn't change the order of
+--- lib/Transforms/Scalar/LoopStrengthReduce.cpp 2014-11-18 23:49:26.000000000 -0800
++++ lib/Transforms/Scalar/LoopStrengthReduce.cpp 2015-11-29 08:54:51.641136545 -0800
+@@ -1933,9 +1933,10 @@
+ // NOTE: we could handle setcc instructions with multiple uses here, but
+ // InstCombine does it as well for simple uses, it's not clear that it
+ // occurs enough in real life to handle.
+- CondUse = UI;
++ CondUse = &*UI;
+ return true;
+ }
++
+ return false;
+ }
+
+@@ -2203,7 +2204,7 @@
+ ICmpInst *OldCond = Cond;
+ Cond = cast<ICmpInst>(Cond->clone());
+ Cond->setName(L->getHeader()->getName() + ".termcond");
+- ExitingBlock->getInstList().insert(TermBr, Cond);
++ ExitingBlock->getInstList().insert(TermBr->getIterator(), Cond);
+
+ // Clone the IVUse, as the old use still exists!
+ CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
+@@ -2782,20 +2783,21 @@
+ for (BasicBlock::iterator I = (*BBIter)->begin(), E = (*BBIter)->end();
+ I != E; ++I) {
+ // Skip instructions that weren't seen by IVUsers analysis.
+- if (isa<PHINode>(I) || !IU.isIVUserOrOperand(I))
++ if (isa<PHINode>(I) || !IU.isIVUserOrOperand(&*I))
+ continue;
+
+ // Ignore users that are part of a SCEV expression. This way we only
+ // consider leaf IV Users. This effectively rediscovers a portion of
+ // IVUsers analysis but in program order this time.
+- if (SE.isSCEVable(I->getType()) && !isa<SCEVUnknown>(SE.getSCEV(I)))
++ if (SE.isSCEVable(I->getType()) && !isa<SCEVUnknown>(SE.getSCEV(&*I)))
+ continue;
+
+ // Remove this instruction from any NearUsers set it may be in.
+ for (unsigned ChainIdx = 0, NChains = IVChainVec.size();
+ ChainIdx < NChains; ++ChainIdx) {
+- ChainUsersVec[ChainIdx].NearUsers.erase(I);
++ ChainUsersVec[ChainIdx].NearUsers.erase(&*I);
+ }
++
+ // Search for operands that can be chained.
+ SmallPtrSet<Instruction*, 4> UniqueOperands;
+ User::op_iterator IVOpEnd = I->op_end();
+@@ -2803,7 +2805,7 @@
+ while (IVOpIter != IVOpEnd) {
+ Instruction *IVOpInst = cast<Instruction>(*IVOpIter);
+ if (UniqueOperands.insert(IVOpInst).second)
+- ChainInstruction(I, IVOpInst, ChainUsersVec);
++ ChainInstruction(&*I, IVOpInst, ChainUsersVec);
+ IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
+ }
+ } // Continue walking down the instructions.
+@@ -4437,14 +4439,14 @@
+ // instead of at the end, so that it can be used for other expansions.
+ if (IDom == Inst->getParent() &&
+ (!BetterPos || !DT.dominates(Inst, BetterPos)))
+- BetterPos = std::next(BasicBlock::iterator(Inst));
++ BetterPos = &(*std::next(BasicBlock::iterator(Inst)));
+ }
+ if (!AllDominate)
+ break;
+ if (BetterPos)
+- IP = BetterPos;
++ IP = BetterPos->getIterator();
+ else
+- IP = Tentative;
++ IP = Tentative->getIterator();
+ }
+
+ return IP;
+@@ -4511,7 +4513,8 @@
+ // Set IP below instructions recently inserted by SCEVExpander. This keeps the
+ // IP consistent across expansions and allows the previously inserted
+ // instructions to be reused by subsequent expansion.
+- while (Rewriter.isInsertedInstruction(IP) && IP != LowestIP) ++IP;
++ while (Rewriter.isInsertedInstruction(&*IP) && IP != LowestIP)
++ ++IP;
+
+ return IP;
+ }
+@@ -4563,7 +4566,7 @@
+ LF.UserInst, LF.OperandValToReplace,
+ Loops, SE, DT);
+
+- Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, nullptr, IP)));
++ Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, nullptr, &*IP)));
+ }
+
+ // Expand the ScaledReg portion.
+@@ -4581,14 +4584,14 @@
+ // Expand ScaleReg as if it was part of the base regs.
+ if (F.Scale == 1)
+ Ops.push_back(
+- SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr, IP)));
++ SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr, &*IP)));
+ else {
+ // An interesting way of "folding" with an icmp is to use a negated
+ // scale, which we'll implement by inserting it into the other operand
+ // of the icmp.
+ assert(F.Scale == -1 &&
+ "The only scale supported by ICmpZero uses is -1!");
+- ICmpScaledV = Rewriter.expandCodeFor(ScaledS, nullptr, IP);
++ ICmpScaledV = Rewriter.expandCodeFor(ScaledS, nullptr, &*IP);
+ }
+ } else {
+ // Otherwise just expand the scaled register and an explicit scale,
+@@ -4598,11 +4601,11 @@
+ // Unless the addressing mode will not be folded.
+ if (!Ops.empty() && LU.Kind == LSRUse::Address &&
+ isAMCompletelyFolded(TTI, LU, F)) {
+- Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
++ Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, &*IP);
+ Ops.clear();
+ Ops.push_back(SE.getUnknown(FullV));
+ }
+- ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr, IP));
++ ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr, &*IP));
+ if (F.Scale != 1)
+ ScaledS =
+ SE.getMulExpr(ScaledS, SE.getConstant(ScaledS->getType(), F.Scale));
+@@ -4614,7 +4617,7 @@
+ if (F.BaseGV) {
+ // Flush the operand list to suppress SCEVExpander hoisting.
+ if (!Ops.empty()) {
+- Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
++ Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, &*IP);
+ Ops.clear();
+ Ops.push_back(SE.getUnknown(FullV));
+ }
+@@ -4624,7 +4627,7 @@
+ // Flush the operand list to suppress SCEVExpander hoisting of both folded and
+ // unfolded offsets. LSR assumes they both live next to their uses.
+ if (!Ops.empty()) {
+- Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
++ Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, &*IP);
+ Ops.clear();
+ Ops.push_back(SE.getUnknown(FullV));
+ }
+@@ -4636,7 +4639,7 @@
+ // The other interesting way of "folding" with an ICmpZero is to use a
+ // negated immediate.
+ if (!ICmpScaledV)
+- ICmpScaledV = ConstantInt::get(IntTy, -(uint64_t)Offset);
++ ICmpScaledV = ConstantInt::get(IntTy, -((uint64_t) Offset));
+ else {
+ Ops.push_back(SE.getUnknown(ICmpScaledV));
+ ICmpScaledV = ConstantInt::get(IntTy, Offset);
+@@ -4660,7 +4663,7 @@
+ const SCEV *FullS = Ops.empty() ?
+ SE.getConstant(IntTy, 0) :
+ SE.getAddExpr(Ops);
+- Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
++ Value *FullV = Rewriter.expandCodeFor(FullS, Ty, &*IP);
+
+ // We're done expanding now, so reset the rewriter.
+ Rewriter.clearPostInc();
+@@ -4759,7 +4762,8 @@
+ if (!Pair.second)
+ PN->setIncomingValue(i, Pair.first->second);
+ else {
+- Value *FullV = Expand(LF, F, BB->getTerminator(), Rewriter, DeadInsts);
++ Value *FullV = Expand(LF, F, BB->getTerminator()->getIterator(),
++ Rewriter, DeadInsts);
+
+ // If this is reuse-by-noop-cast, insert the noop cast.
+ Type *OpTy = LF.OperandValToReplace->getType();
+@@ -4789,7 +4793,8 @@
+ if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
+ RewriteForPHI(PN, LF, F, Rewriter, DeadInsts, P);
+ } else {
+- Value *FullV = Expand(LF, F, LF.UserInst, Rewriter, DeadInsts);
++ Value *FullV =
++ Expand(LF, F, LF.UserInst->getIterator(), Rewriter, DeadInsts);
+
+ // If this is reuse-by-noop-cast, insert the noop cast.
+ Type *OpTy = LF.OperandValToReplace->getType();
+--- lib/Transforms/Scalar/LoopUnswitch.cpp 2015-01-04 04:03:27.000000000 -0800
++++ lib/Transforms/Scalar/LoopUnswitch.cpp 2015-11-28 17:55:30.857922905 -0800
+@@ -737,7 +737,7 @@
+ // without actually branching to it (the exit block should be dominated by the
+ // loop header, not the preheader).
+ assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
+- BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
++ BasicBlock *NewExit = SplitBlock(ExitBlock, &(ExitBlock->front()), this);
+
+ // Okay, now we have a position to branch from and a position to branch to,
+ // insert the new conditional branch.
+@@ -832,8 +832,9 @@
+
+ // Splice the newly inserted blocks into the function right before the
+ // original preheader.
+- F->getBasicBlockList().splice(NewPreheader, F->getBasicBlockList(),
+- NewBlocks[0], F->end());
++ F->getBasicBlockList().splice(NewPreheader->getIterator(),
++ F->getBasicBlockList(),
++ NewBlocks[0]->getIterator(), F->end());
+
+ // FIXME: We could register any cloned assumptions instead of clearing the
+ // whole function's cache.
+@@ -875,7 +876,7 @@
+
+ if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
+ PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
+- ExitSucc->getFirstInsertionPt());
++ &*ExitSucc->getFirstInsertionPt());
+
+ for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
+ I != E; ++I) {
+@@ -891,7 +892,8 @@
+ for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
+ for (BasicBlock::iterator I = NewBlocks[i]->begin(),
+ E = NewBlocks[i]->end(); I != E; ++I)
+- RemapInstruction(I, VMap,RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
++ RemapInstruction(&*I, VMap,
++ RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
+
+ // Rewrite the original preheader to select between versions of the loop.
+ BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
+@@ -1136,8 +1138,9 @@
+ Succ->replaceAllUsesWith(Pred);
+
+ // Move all of the successor contents from Succ to Pred.
+- Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
+- Succ->end());
++ Pred->getInstList().splice(BI->getIterator(),
++ Succ->getInstList(),
++ Succ->begin(), Succ->end());
+ LPM->deleteSimpleAnalysisValue(BI, L);
+ BI->eraseFromParent();
+ RemoveFromWorklist(BI, Worklist);
+--- lib/Transforms/Scalar/LowerAtomic.cpp 2014-06-13 07:24:07.000000000 -0700
++++ lib/Transforms/Scalar/LowerAtomic.cpp 2015-11-28 17:57:32.665949990 -0800
+@@ -22,7 +22,7 @@
+ #define DEBUG_TYPE "loweratomic"
+
+ static bool LowerAtomicCmpXchgInst(AtomicCmpXchgInst *CXI) {
+- IRBuilder<> Builder(CXI->getParent(), CXI);
++ IRBuilder<> Builder(CXI);
+ Value *Ptr = CXI->getPointerOperand();
+ Value *Cmp = CXI->getCompareOperand();
+ Value *Val = CXI->getNewValOperand();
+@@ -41,7 +41,7 @@
+ }
+
+ static bool LowerAtomicRMWInst(AtomicRMWInst *RMWI) {
+- IRBuilder<> Builder(RMWI->getParent(), RMWI);
++ IRBuilder<> Builder(RMWI);
+ Value *Ptr = RMWI->getPointerOperand();
+ Value *Val = RMWI->getValOperand();
+
+@@ -120,7 +120,8 @@
+ return false;
+ bool Changed = false;
+ for (BasicBlock::iterator DI = BB.begin(), DE = BB.end(); DI != DE; ) {
+- Instruction *Inst = DI++;
++ Instruction *Inst = &*DI;
++ ++DI;
+ if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
+ Changed |= LowerFenceInst(FI);
+ else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(Inst))
+--- lib/Transforms/Scalar/MemCpyOptimizer.cpp 2015-02-07 11:39:14.000000000 -0800
++++ lib/Transforms/Scalar/MemCpyOptimizer.cpp 2015-11-28 18:08:18.813257513 -0800
+@@ -385,7 +385,7 @@
+ // are stored.
+ MemsetRanges Ranges(*DL);
+
+- BasicBlock::iterator BI = StartInst;
++ BasicBlock::iterator BI(StartInst);
+ for (++BI; !isa<TerminatorInst>(BI); ++BI) {
+ if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
+ // If the instruction is readnone, ignore it, otherwise bail out. We
+@@ -440,7 +440,7 @@
+ // If we create any memsets, we put it right before the first instruction that
+ // isn't part of the memset block. This ensure that the memset is dominated
+ // by any addressing instruction needed by the start of the block.
+- IRBuilder<> Builder(BI);
++ IRBuilder<> Builder(&*BI);
+
+ // Now that we have full information about ranges, loop over the ranges and
+ // emit memset's for anything big enough to be worthwhile.
+@@ -513,8 +513,8 @@
+ // the call and the store.
+ AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
+ AliasAnalysis::Location StoreLoc = AA.getLocation(SI);
+- for (BasicBlock::iterator I = --BasicBlock::iterator(SI),
+- E = C; I != E; --I) {
++ for (BasicBlock::iterator I = --SI->getIterator(),
++ E = C->getIterator(); I != E; --I) {
+ if (AA.getModRefInfo(&*I, StoreLoc) != AliasAnalysis::NoModRef) {
+ C = nullptr;
+ break;
+@@ -556,7 +556,7 @@
+ if (Value *ByteVal = isBytewiseValue(SI->getOperand(0)))
+ if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
+ ByteVal)) {
+- BBI = I; // Don't invalidate iterator.
++ BBI = I->getIterator(); // Don't invalidate iterator.
+ return true;
+ }
+
+@@ -569,7 +569,7 @@
+ if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
+ if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
+ MSI->getValue())) {
+- BBI = I; // Don't invalidate iterator.
++ BBI = I->getIterator(); // Don't invalidate iterator.
+ return true;
+ }
+ return false;
+@@ -808,8 +808,8 @@
+ // NOTE: This is conservative, it will stop on any read from the source loc,
+ // not just the defining memcpy.
+ MemDepResult SourceDep =
+- MD->getPointerDependencyFrom(AA.getLocationForSource(MDep),
+- false, M, M->getParent());
++ MD->getPointerDependencyFrom(AA.getLocationForSource(MDep), false,
++ M->getIterator(), M->getParent());
+ if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
+ return false;
+
+@@ -898,8 +898,9 @@
+ }
+
+ AliasAnalysis::Location SrcLoc = AliasAnalysis::getLocationForSource(M);
+- MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(SrcLoc, true,
+- M, M->getParent());
++ MemDepResult SrcDepInfo =
++ MD->getPointerDependencyFrom(SrcLoc, true,
++ M->getIterator(), M->getParent());
+ if (SrcDepInfo.isClobber()) {
+ if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
+ return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue());
+@@ -967,7 +968,8 @@
+ uint64_t ByValSize = DL->getTypeAllocSize(ByValTy);
+ MemDepResult DepInfo =
+ MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize),
+- true, CS.getInstruction(),
++ true,
++ CS.getInstruction()->getIterator(),
+ CS.getInstruction()->getParent());
+ if (!DepInfo.isClobber())
+ return false;
+@@ -1012,7 +1014,9 @@
+ // not just the defining memcpy.
+ MemDepResult SourceDep =
+ MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep),
+- false, CS.getInstruction(), MDep->getParent());
++ false,
++ CS.getInstruction()->getIterator(),
++ MDep->getParent());
+ if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
+ return false;
+
+@@ -1039,7 +1043,8 @@
+ for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
+ for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
+ // Avoid invalidating the iterator.
+- Instruction *I = BI++;
++ Instruction *I = &*BI;
++ ++BI;
+
+ bool RepeatInstruction = false;
+
+--- lib/Transforms/Scalar/MergedLoadStoreMotion.cpp 2015-02-17 14:03:58.000000000 -0800
++++ lib/Transforms/Scalar/MergedLoadStoreMotion.cpp 2015-11-28 18:11:58.690419443 -0800
+@@ -256,7 +256,7 @@
+
+ for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end(); BBI != BBE;
+ ++BBI) {
+- Instruction *Inst = BBI;
++ Instruction *Inst = &*BBI;
+
+ // Only merge and hoist loads when their result in used only in BB
+ if (!isa<LoadInst>(Inst) || Inst->isUsedOutsideOfBlock(BB1))
+@@ -367,8 +367,7 @@
+ int NLoads = 0;
+ for (BasicBlock::iterator BBI = Succ0->begin(), BBE = Succ0->end();
+ BBI != BBE;) {
+-
+- Instruction *I = BBI;
++ Instruction *I = &*BBI;
+ ++BBI;
+
+ // Only move non-simple (atomic, volatile) loads.
+@@ -448,7 +447,7 @@
+ Value *Opd2 = S1->getValueOperand();
+ if (Opd1 != Opd2) {
+ NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink",
+- BB->begin());
++ &BB->front());
+ NewPN->addIncoming(Opd1, S0->getParent());
+ NewPN->addIncoming(Opd2, S1->getParent());
+ if (NewPN->getType()->getScalarType()->isPointerTy()) {
+@@ -493,7 +492,7 @@
+ StoreInst *SNew = (StoreInst *)(S0->clone());
+ Instruction *ANew = A0->clone();
+ AA->copyValue(S0, SNew);
+- SNew->insertBefore(InsertPt);
++ SNew->insertBefore(&*InsertPt);
+ ANew->insertBefore(SNew);
+
+ assert(S0->getParent() == A0->getParent());
+@@ -588,7 +587,8 @@
+ // Merge unconditional branches, allowing PRE to catch more
+ // optimization opportunities.
+ for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
+- BasicBlock *BB = FI++;
++ BasicBlock *BB = &*FI;
++ ++FI;
+
+ // Hoist equivalent loads and sink stores
+ // outside diamonds when possible
+--- lib/Transforms/Scalar/PartiallyInlineLibCalls.cpp 2014-08-01 16:21:21.000000000 -0700
++++ lib/Transforms/Scalar/PartiallyInlineLibCalls.cpp 2015-11-28 18:13:26.025414765 -0800
+@@ -152,7 +152,7 @@
+ Phi->addIncoming(Call, &CurrBB);
+ Phi->addIncoming(LibCall, LibCallBB);
+
+- BB = JoinBB;
++ BB = JoinBB->getIterator();
+ return true;
+ }
+
+--- lib/Transforms/Scalar/Reassociate.cpp 2014-12-12 06:44:12.000000000 -0800
++++ lib/Transforms/Scalar/Reassociate.cpp 2015-11-29 08:56:09.229859750 -0800
+@@ -295,7 +295,7 @@
+ // we cannot move. This ensures that the ranks for these instructions are
+ // all different in the block.
+ for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
+- if (isUnmovableInstruction(I))
++ if (isUnmovableInstruction(&*I))
+ ValueRankMap[&*I] = ++BBRank;
+ }
+ }
+@@ -968,14 +968,14 @@
+ if (InvokeInst *II = dyn_cast<InvokeInst>(InstInput)) {
+ InsertPt = II->getNormalDest()->begin();
+ } else {
+- InsertPt = InstInput;
+- ++InsertPt;
++ InsertPt = ++InstInput->getIterator();
+ }
+ while (isa<PHINode>(InsertPt)) ++InsertPt;
+ } else {
+ InsertPt = TheNeg->getParent()->getParent()->getEntryBlock().begin();
+ }
+- TheNeg->moveBefore(InsertPt);
++
++ TheNeg->moveBefore(&*InsertPt);
+ return TheNeg;
+ }
+
+@@ -1160,7 +1160,7 @@
+ return nullptr;
+ }
+
+- BasicBlock::iterator InsertPt = BO; ++InsertPt;
++ BasicBlock::iterator InsertPt = ++BO->getIterator();
+
+ // If this was just a single multiply, remove the multiply and return the only
+ // remaining operand.
+@@ -1173,7 +1173,7 @@
+ }
+
+ if (NeedsNegate)
+- V = CreateNeg(V, "neg", InsertPt, BO);
++ V = CreateNeg(V, "neg", &*InsertPt, BO);
+
+ return V;
+ }
+@@ -2262,10 +2262,10 @@
+ for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
+ // Optimize every instruction in the basic block.
+ for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE; )
+- if (isInstructionTriviallyDead(II)) {
+- EraseInst(II++);
++ if (isInstructionTriviallyDead(&*II)) {
++ EraseInst(&*II++);
+ } else {
+- OptimizeInst(II);
++ OptimizeInst(&*II);
+ assert(II->getParent() == BI && "Moved to a different block!");
+ ++II;
+ }
+--- lib/Transforms/Scalar/Reg2Mem.cpp 2015-01-12 19:46:47.000000000 -0800
++++ lib/Transforms/Scalar/Reg2Mem.cpp 2015-11-28 18:22:35.790368260 -0800
+@@ -85,7 +85,7 @@
+ CastInst *AllocaInsertionPoint =
+ new BitCastInst(Constant::getNullValue(Type::getInt32Ty(F.getContext())),
+ Type::getInt32Ty(F.getContext()),
+- "reg2mem alloca point", I);
++ "reg2mem alloca point", &*I);
+
+ // Find the escaped instructions. But don't create stack slots for
+ // allocas in entry block.
+@@ -95,7 +95,7 @@
+ for (BasicBlock::iterator iib = ibb->begin(), iie = ibb->end();
+ iib != iie; ++iib) {
+ if (!(isa<AllocaInst>(iib) && iib->getParent() == BBEntry) &&
+- valueEscapes(iib)) {
++ valueEscapes(&*iib)) {
+ WorkList.push_front(&*iib);
+ }
+ }
+--- lib/Transforms/Scalar/SCCP.cpp 2014-11-18 23:49:26.000000000 -0800
++++ lib/Transforms/Scalar/SCCP.cpp 2015-11-28 19:12:24.103813993 -0800
+@@ -1125,7 +1125,7 @@
+ // entry block executable and merge in the actual arguments to the call into
+ // the formal arguments of the function.
+ if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
+- MarkBlockExecutable(F->begin());
++ MarkBlockExecutable(&F->front());
+
+ // Propagate information from this call site into the callee.
+ CallSite::arg_iterator CAI = CS.arg_begin();
+@@ -1134,17 +1134,17 @@
+ // If this argument is byval, and if the function is not readonly, there
+ // will be an implicit copy formed of the input aggregate.
+ if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
+- markOverdefined(AI);
++ markOverdefined(&*AI);
+ continue;
+ }
+
+ if (StructType *STy = dyn_cast<StructType>(AI->getType())) {
+ for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
+ LatticeVal CallArg = getStructValueState(*CAI, i);
+- mergeInValue(getStructValueState(AI, i), AI, CallArg);
++ mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg);
+ }
+ } else {
+- mergeInValue(AI, getValueState(*CAI));
++ mergeInValue(&*AI, getValueState(*CAI));
+ }
+ }
+ }
+@@ -1245,18 +1245,18 @@
+ /// even if X isn't defined.
+ bool SCCPSolver::ResolvedUndefsIn(Function &F) {
+ for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
+- if (!BBExecutable.count(BB))
++ if (!BBExecutable.count(&*BB))
+ continue;
+
+- for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
++ for (Instruction &I : *BB) {
+ // Look for instructions which produce undef values.
+- if (I->getType()->isVoidTy()) continue;
++ if (I.getType()->isVoidTy()) continue;
+
+- if (StructType *STy = dyn_cast<StructType>(I->getType())) {
++ if (StructType *STy = dyn_cast<StructType>(I.getType())) {
+ // Only a few things that can be structs matter for undef.
+
+ // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
+- if (CallSite CS = CallSite(I))
++ if (CallSite CS = CallSite(&I))
+ if (Function *F = CS.getCalledFunction())
+ if (MRVFunctionsTracked.count(F))
+ continue;
+@@ -1269,14 +1269,14 @@
+ // Send the results of everything else to overdefined. We could be
+ // more precise than this but it isn't worth bothering.
+ for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
+- LatticeVal &LV = getStructValueState(I, i);
++ LatticeVal &LV = getStructValueState(&I, i);
+ if (LV.isUndefined())
+- markOverdefined(LV, I);
++ markOverdefined(LV, &I);
+ }
+ continue;
+ }
+
+- LatticeVal &LV = getValueState(I);
++ LatticeVal &LV = getValueState(&I);
+ if (!LV.isUndefined()) continue;
+
+ // extractvalue is safe; check here because the argument is a struct.
+@@ -1286,24 +1286,24 @@
+ // Compute the operand LatticeVals, for convenience below.
+ // Anything taking a struct is conservatively assumed to require
+ // overdefined markings.
+- if (I->getOperand(0)->getType()->isStructTy()) {
+- markOverdefined(I);
++ if (I.getOperand(0)->getType()->isStructTy()) {
++ markOverdefined(&I);
+ return true;
+ }
+- LatticeVal Op0LV = getValueState(I->getOperand(0));
++ LatticeVal Op0LV = getValueState(I.getOperand(0));
+ LatticeVal Op1LV;
+- if (I->getNumOperands() == 2) {
+- if (I->getOperand(1)->getType()->isStructTy()) {
+- markOverdefined(I);
++ if (I.getNumOperands() == 2) {
++ if (I.getOperand(1)->getType()->isStructTy()) {
++ markOverdefined(&I);
+ return true;
+ }
+
+- Op1LV = getValueState(I->getOperand(1));
++ Op1LV = getValueState(I.getOperand(1));
+ }
+ // If this is an instructions whose result is defined even if the input is
+ // not fully defined, propagate the information.
+- Type *ITy = I->getType();
+- switch (I->getOpcode()) {
++ Type *ITy = I.getType();
++ switch (I.getOpcode()) {
+ case Instruction::Add:
+ case Instruction::Sub:
+ case Instruction::Trunc:
+@@ -1317,9 +1317,9 @@
+ case Instruction::FRem:
+ // Floating-point binary operation: be conservative.
+ if (Op0LV.isUndefined() && Op1LV.isUndefined())
+- markForcedConstant(I, Constant::getNullValue(ITy));
++ markForcedConstant(&I, Constant::getNullValue(ITy));
+ else
+- markOverdefined(I);
++ markOverdefined(&I);
+ return true;
+ case Instruction::ZExt:
+ case Instruction::SExt:
+@@ -1331,7 +1331,7 @@
+ case Instruction::SIToFP:
+ case Instruction::UIToFP:
+ // undef -> 0; some outputs are impossible
+- markForcedConstant(I, Constant::getNullValue(ITy));
++ markForcedConstant(&I, Constant::getNullValue(ITy));
+ return true;
+ case Instruction::Mul:
+ case Instruction::And:
+@@ -1340,7 +1340,7 @@
+ break;
+ // undef * X -> 0. X could be zero.
+ // undef & X -> 0. X could be zero.
+- markForcedConstant(I, Constant::getNullValue(ITy));
++ markForcedConstant(&I, Constant::getNullValue(ITy));
+ return true;
+
+ case Instruction::Or:
+@@ -1348,7 +1348,7 @@
+ if (Op0LV.isUndefined() && Op1LV.isUndefined())
+ break;
+ // undef | X -> -1. X could be -1.
+- markForcedConstant(I, Constant::getAllOnesValue(ITy));
++ markForcedConstant(&I, Constant::getAllOnesValue(ITy));
+ return true;
+
+ case Instruction::Xor:
+@@ -1356,7 +1356,7 @@
+ // necessary, but we try to be nice to people who expect this
+ // behavior in simple cases
+ if (Op0LV.isUndefined() && Op1LV.isUndefined()) {
+- markForcedConstant(I, Constant::getNullValue(ITy));
++ markForcedConstant(&I, Constant::getNullValue(ITy));
+ return true;
+ }
+ // undef ^ X -> undef
+@@ -1372,7 +1372,7 @@
+
+ // undef / X -> 0. X could be maxint.
+ // undef % X -> 0. X could be 1.
+- markForcedConstant(I, Constant::getNullValue(ITy));
++ markForcedConstant(&I, Constant::getNullValue(ITy));
+ return true;
+
+ case Instruction::AShr:
+@@ -1380,7 +1380,7 @@
+ if (Op1LV.isUndefined()) break;
+
+ // undef >>a X -> all ones
+- markForcedConstant(I, Constant::getAllOnesValue(ITy));
++ markForcedConstant(&I, Constant::getAllOnesValue(ITy));
+ return true;
+ case Instruction::LShr:
+ case Instruction::Shl:
+@@ -1390,17 +1390,17 @@
+
+ // undef << X -> 0
+ // undef >> X -> 0
+- markForcedConstant(I, Constant::getNullValue(ITy));
++ markForcedConstant(&I, Constant::getNullValue(ITy));
+ return true;
+ case Instruction::Select:
+- Op1LV = getValueState(I->getOperand(1));
++ Op1LV = getValueState(I.getOperand(1));
+ // undef ? X : Y -> X or Y. There could be commonality between X/Y.
+ if (Op0LV.isUndefined()) {
+ if (!Op1LV.isConstant()) // Pick the constant one if there is any.
+- Op1LV = getValueState(I->getOperand(2));
++ Op1LV = getValueState(I.getOperand(2));
+ } else if (Op1LV.isUndefined()) {
+ // c ? undef : undef -> undef. No change.
+- Op1LV = getValueState(I->getOperand(2));
++ Op1LV = getValueState(I.getOperand(2));
+ if (Op1LV.isUndefined())
+ break;
+ // Otherwise, c ? undef : x -> x.
+@@ -1409,9 +1409,9 @@
+ }
+
+ if (Op1LV.isConstant())
+- markForcedConstant(I, Op1LV.getConstant());
++ markForcedConstant(&I, Op1LV.getConstant());
+ else
+- markOverdefined(I);
++ markOverdefined(&I);
+ return true;
+ case Instruction::Load:
+ // A load here means one of two things: a load of undef from a global,
+@@ -1420,9 +1420,9 @@
+ break;
+ case Instruction::ICmp:
+ // X == undef -> undef. Other comparisons get more complicated.
+- if (cast<ICmpInst>(I)->isEquality())
++ if (cast<ICmpInst>(&I)->isEquality())
+ break;
+- markOverdefined(I);
++ markOverdefined(&I);
+ return true;
+ case Instruction::Call:
+ case Instruction::Invoke: {
+@@ -1431,19 +1431,19 @@
+ // 2. It could be constant-foldable.
+ // Because of the way we solve return values, tracked calls must
+ // never be marked overdefined in ResolvedUndefsIn.
+- if (Function *F = CallSite(I).getCalledFunction())
++ if (Function *F = CallSite(&I).getCalledFunction())
+ if (TrackedRetVals.count(F))
+ break;
+
+ // If the call is constant-foldable, we mark it overdefined because
+ // we do not know what return values are valid.
+- markOverdefined(I);
++ markOverdefined(&I);
+ return true;
+ }
+ default:
+ // If we don't know what should happen here, conservatively mark it
+ // overdefined.
+- markOverdefined(I);
++ markOverdefined(&I);
+ return true;
+ }
+ }
+@@ -1461,7 +1461,7 @@
+ // false.
+ if (isa<UndefValue>(BI->getCondition())) {
+ BI->setCondition(ConstantInt::getFalse(BI->getContext()));
+- markEdgeExecutable(BB, TI->getSuccessor(1));
++ markEdgeExecutable(&*BB, TI->getSuccessor(1));
+ return true;
+ }
+
+@@ -1483,7 +1483,7 @@
+ // the first constant.
+ if (isa<UndefValue>(SI->getCondition())) {
+ SI->setCondition(SI->case_begin().getCaseValue());
+- markEdgeExecutable(BB, SI->case_begin().getCaseSuccessor());
++ markEdgeExecutable(&*BB, SI->case_begin().getCaseSuccessor());
+ return true;
+ }
+
+@@ -1540,8 +1540,7 @@
+ Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
+ while (EndInst != BB->begin()) {
+ // Delete the next to last instruction.
+- BasicBlock::iterator I = EndInst;
+- Instruction *Inst = --I;
++ Instruction *Inst = &*--EndInst->getIterator();
+ if (!Inst->use_empty())
+ Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
+ if (isa<LandingPadInst>(Inst)) {
+@@ -1567,11 +1566,11 @@
+ SCCPSolver Solver(DL, TLI);
+
+ // Mark the first block of the function as being executable.
+- Solver.MarkBlockExecutable(F.begin());
++ Solver.MarkBlockExecutable(&F.front());
+
+ // Mark all arguments to the function as being overdefined.
+- for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
+- Solver.markAnythingOverdefined(AI);
++ for (Argument &AI : F.args())
++ Solver.markAnythingOverdefined(&AI);
+
+ // Solve for constants.
+ bool ResolvedUndefs = true;
+@@ -1588,8 +1587,8 @@
+ // as we cannot modify the CFG of the function.
+
+ for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
+- if (!Solver.isBlockExecutable(BB)) {
+- DeleteInstructionInBlock(BB);
++ if (!Solver.isBlockExecutable(&*BB)) {
++ DeleteInstructionInBlock(&*BB);
+ MadeChanges = true;
+ continue;
+ }
+@@ -1598,7 +1597,7 @@
+ // constants if we have found them to be of constant values.
+ //
+ for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
+- Instruction *Inst = BI++;
++ Instruction *Inst = &*BI++;
+ if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
+ continue;
+
+@@ -1712,36 +1711,34 @@
+ // If this is a strong or ODR definition of this function, then we can
+ // propagate information about its result into callsites of it.
+ if (!F->mayBeOverridden())
+- Solver.AddTrackedFunction(F);
++ Solver.AddTrackedFunction(&*F);
+
+ // If this function only has direct calls that we can see, we can track its
+ // arguments and return value aggressively, and can assume it is not called
+ // unless we see evidence to the contrary.
+ if (F->hasLocalLinkage()) {
+- if (AddressIsTaken(F))
+- AddressTakenFunctions.insert(F);
++ if (AddressIsTaken(&*F))
++ AddressTakenFunctions.insert(&*F);
+ else {
+- Solver.AddArgumentTrackedFunction(F);
++ Solver.AddArgumentTrackedFunction(&*F);
+ continue;
+ }
+ }
+
+ // Assume the function is called.
+- Solver.MarkBlockExecutable(F->begin());
++ Solver.MarkBlockExecutable(&F->front());
+
+ // Assume nothing about the incoming arguments.
+- for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
+- AI != E; ++AI)
+- Solver.markAnythingOverdefined(AI);
++ for (Argument &AI : F->args())
++ Solver.markAnythingOverdefined(&AI);
+ }
+
+ // Loop over global variables. We inform the solver about any internal global
+ // variables that do not have their 'addresses taken'. If they don't have
+ // their addresses taken, we can propagate constants through them.
+- for (Module::global_iterator G = M.global_begin(), E = M.global_end();
+- G != E; ++G)
+- if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
+- Solver.TrackValueOfGlobalVariable(G);
++ for (GlobalVariable &G : M.globals())
++ if (!G.isConstant() && G.hasLocalLinkage() && !AddressIsTaken(&G))
++ Solver.TrackValueOfGlobalVariable(&G);
+
+ // Solve for constants.
+ bool ResolvedUndefs = true;
+@@ -1762,7 +1759,10 @@
+ SmallVector<BasicBlock*, 512> BlocksToErase;
+
+ for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
+- if (Solver.isBlockExecutable(F->begin())) {
++ if (F->isDeclaration())
++ continue;
++
++ if (Solver.isBlockExecutable(&F->front())) {
+ for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
+ AI != E; ++AI) {
+ if (AI->use_empty() || AI->getType()->isStructTy()) continue;
+@@ -1770,7 +1770,7 @@
+ // TODO: Could use getStructLatticeValueFor to find out if the entire
+ // result is a constant and replace it entirely if so.
+
+- LatticeVal IV = Solver.getLatticeValueFor(AI);
++ LatticeVal IV = Solver.getLatticeValueFor(&*AI);
+ if (IV.isOverdefined()) continue;
+
+ Constant *CST = IV.isConstant() ?
+@@ -1785,29 +1785,29 @@
+ }
+
+ for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
+- if (!Solver.isBlockExecutable(BB)) {
+- DeleteInstructionInBlock(BB);
++ if (!Solver.isBlockExecutable(&*BB)) {
++ DeleteInstructionInBlock(&*BB);
+ MadeChanges = true;
+
+ TerminatorInst *TI = BB->getTerminator();
+ for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
+ BasicBlock *Succ = TI->getSuccessor(i);
+ if (!Succ->empty() && isa<PHINode>(Succ->begin()))
+- TI->getSuccessor(i)->removePredecessor(BB);
++ TI->getSuccessor(i)->removePredecessor(&*BB);
+ }
++
+ if (!TI->use_empty())
+ TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
+ TI->eraseFromParent();
++ new UnreachableInst(M.getContext(), &*BB);
+
+ if (&*BB != &F->front())
+- BlocksToErase.push_back(BB);
+- else
+- new UnreachableInst(M.getContext(), BB);
++ BlocksToErase.push_back(&*BB);
+ continue;
+ }
+
+ for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
+- Instruction *Inst = BI++;
++ Instruction *Inst = &*BI++;
+ if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
+ continue;
+
+--- lib/Transforms/Scalar/SROA.cpp 2015-01-07 18:02:00.000000000 -0800
++++ lib/Transforms/Scalar/SROA.cpp 2015-11-28 19:22:34.615193007 -0800
+@@ -1370,7 +1370,7 @@
+
+ // Ensure that there are no instructions between the PHI and the load that
+ // could store.
+- for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
++ for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
+ if (BBI->mayWriteToMemory())
+ return false;
+
+@@ -2607,7 +2607,8 @@
+ DL.getTypeStoreSizeInBits(LI.getType()) &&
+ "Non-byte-multiple bit width");
+ // Move the insertion point just past the load so that we can refer to it.
+- IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI)));
++ IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI)));
++
+ // Create a placeholder value with the same type as LI to use as the
+ // basis for the new value. This allows us to replace the uses of LI with
+ // the computed value, and then replace the placeholder with LI, leaving
+@@ -3069,7 +3070,7 @@
+ // dominate the PHI.
+ IRBuilderTy PtrBuilder(IRB);
+ if (isa<PHINode>(OldPtr))
+- PtrBuilder.SetInsertPoint(OldPtr->getParent()->getFirstInsertionPt());
++ PtrBuilder.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt());
+ else
+ PtrBuilder.SetInsertPoint(OldPtr);
+ PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
+@@ -3714,7 +3715,7 @@
+ "Cannot represent alloca access size using 64-bit integers!");
+
+ Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
+- IRB.SetInsertPoint(BasicBlock::iterator(LI));
++ IRB.SetInsertPoint(LI);
+
+ DEBUG(dbgs() << " Splitting load: " << *LI << "\n");
+
+@@ -3766,7 +3767,7 @@
+ }
+
+ Value *StoreBasePtr = SI->getPointerOperand();
+- IRB.SetInsertPoint(BasicBlock::iterator(SI));
++ IRB.SetInsertPoint(SI);
+
+ DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n");
+
+@@ -3855,7 +3856,7 @@
+ if (SplitLoads) {
+ PLoad = (*SplitLoads)[Idx];
+ } else {
+- IRB.SetInsertPoint(BasicBlock::iterator(LI));
++ IRB.SetInsertPoint(LI);
+ PLoad = IRB.CreateAlignedLoad(
+ getAdjustedPtr(IRB, *DL, LoadBasePtr,
+ APInt(DL->getPointerSizeInBits(), PartOffset),
+@@ -3865,7 +3866,7 @@
+ }
+
+ // And store this partition.
+- IRB.SetInsertPoint(BasicBlock::iterator(SI));
++ IRB.SetInsertPoint(SI);
+ StoreInst *PStore = IRB.CreateAlignedStore(
+ PLoad, getAdjustedPtr(IRB, *DL, StoreBasePtr,
+ APInt(DL->getPointerSizeInBits(), PartOffset),
+--- lib/Transforms/Scalar/SampleProfile.cpp 2014-11-18 23:49:26.000000000 -0800
++++ lib/Transforms/Scalar/SampleProfile.cpp 2016-01-23 20:40:41.000000000 -0800
+@@ -54,8 +54,10 @@
+
+ // Command line option to specify the file to read samples from. This is
+ // mainly used for debugging.
+-static cl::opt<std::string> SampleProfileFile(
+- "sample-profile-file", cl::init(""), cl::value_desc("filename"),
++static std::string EmptyInitString("");
++static cl::opt<std::string>
++SampleProfileFile("sample-profile-file", cl::init(EmptyInitString),
++ cl::value_desc("filename"),
+ cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
+ static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
+ "sample-profile-max-propagate-iterations", cl::init(100),
+--- lib/Transforms/Scalar/ScalarReplAggregates.cpp 2015-01-04 04:03:27.000000000 -0800
++++ lib/Transforms/Scalar/ScalarReplAggregates.cpp 2015-11-28 18:31:24.445308022 -0800
+@@ -382,8 +382,9 @@
+ // Create and insert the integer alloca.
+ NewTy = IntegerType::get(AI->getContext(), BitWidth);
+ }
++
+ AllocaInst *NewAI = new AllocaInst(NewTy, nullptr, "",
+- AI->getParent()->begin());
++ &AI->getParent()->front());
+ ConvertUsesToScalar(AI, NewAI, 0, nullptr);
+ return NewAI;
+ }
+@@ -1202,7 +1203,7 @@
+
+ // Ensure that there are no instructions between the PHI and the load that
+ // could store.
+- for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
++ for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
+ if (BBI->mayWriteToMemory())
+ return false;
+
+--- lib/Transforms/Scalar/Scalarizer.cpp 2014-11-11 13:30:22.000000000 -0800
++++ lib/Transforms/Scalar/Scalarizer.cpp 2015-11-29 08:58:18.947961675 -0800
+@@ -250,10 +250,9 @@
+ bool Scalarizer::runOnFunction(Function &F) {
+ DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
+ DL = DLP ? &DLP->getDataLayout() : nullptr;
+- for (Function::iterator BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
+- BasicBlock *BB = BBI;
+- for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
+- Instruction *I = II;
++ for (BasicBlock &BB : F) {
++ for (BasicBlock::iterator II = BB.begin(), IE = BB.end(); II != IE;) {
++ Instruction *I = &*II;
+ bool Done = visit(I);
+ ++II;
+ if (Done && I->getType()->isVoidTy())
+@@ -282,7 +281,7 @@
+ }
+ // In the fallback case, just put the scattered before Point and
+ // keep the result local to Point.
+- return Scatterer(Point->getParent(), Point, V);
++ return Scatterer(Point->getParent(), Point->getIterator(), V);
+ }
+
+ // Replace Op with the gathered form of the components in CV. Defer the
+@@ -377,7 +376,7 @@
+ return false;
+
+ unsigned NumElems = VT->getNumElements();
+- IRBuilder<> Builder(I.getParent(), &I);
++ IRBuilder<> Builder(&I);
+ Scatterer Op0 = scatter(&I, I.getOperand(0));
+ Scatterer Op1 = scatter(&I, I.getOperand(1));
+ assert(Op0.size() == NumElems && "Mismatched binary operation");
+@@ -397,7 +396,7 @@
+ return false;
+
+ unsigned NumElems = VT->getNumElements();
+- IRBuilder<> Builder(SI.getParent(), &SI);
++ IRBuilder<> Builder(&SI);
+ Scatterer Op1 = scatter(&SI, SI.getOperand(1));
+ Scatterer Op2 = scatter(&SI, SI.getOperand(2));
+ assert(Op1.size() == NumElems && "Mismatched select");
+@@ -438,7 +437,7 @@
+ if (!VT)
+ return false;
+
+- IRBuilder<> Builder(GEPI.getParent(), &GEPI);
++ IRBuilder<> Builder(&GEPI);
+ unsigned NumElems = VT->getNumElements();
+ unsigned NumIndices = GEPI.getNumIndices();
+
+@@ -472,7 +471,7 @@
+ return false;
+
+ unsigned NumElems = VT->getNumElements();
+- IRBuilder<> Builder(CI.getParent(), &CI);
++ IRBuilder<> Builder(&CI);
+ Scatterer Op0 = scatter(&CI, CI.getOperand(0));
+ assert(Op0.size() == NumElems && "Mismatched cast");
+ ValueVector Res;
+@@ -492,7 +491,7 @@
+
+ unsigned DstNumElems = DstVT->getNumElements();
+ unsigned SrcNumElems = SrcVT->getNumElements();
+- IRBuilder<> Builder(BCI.getParent(), &BCI);
++ IRBuilder<> Builder(&BCI);
+ Scatterer Op0 = scatter(&BCI, BCI.getOperand(0));
+ ValueVector Res;
+ Res.resize(DstNumElems);
+@@ -569,7 +568,7 @@
+ return false;
+
+ unsigned NumElems = VT->getNumElements();
+- IRBuilder<> Builder(PHI.getParent(), &PHI);
++ IRBuilder<> Builder(&PHI);
+ ValueVector Res;
+ Res.resize(NumElems);
+
+@@ -599,7 +598,7 @@
+ return false;
+
+ unsigned NumElems = Layout.VecTy->getNumElements();
+- IRBuilder<> Builder(LI.getParent(), &LI);
++ IRBuilder<> Builder(&LI);
+ Scatterer Ptr = scatter(&LI, LI.getPointerOperand());
+ ValueVector Res;
+ Res.resize(NumElems);
+@@ -623,7 +622,7 @@
+ return false;
+
+ unsigned NumElems = Layout.VecTy->getNumElements();
+- IRBuilder<> Builder(SI.getParent(), &SI);
++ IRBuilder<> Builder(&SI);
+ Scatterer Ptr = scatter(&SI, SI.getPointerOperand());
+ Scatterer Val = scatter(&SI, FullValue);
+
+@@ -653,7 +652,7 @@
+ Value *Res = UndefValue::get(Ty);
+ BasicBlock *BB = Op->getParent();
+ unsigned Count = Ty->getVectorNumElements();
+- IRBuilder<> Builder(BB, Op);
++ IRBuilder<> Builder(Op);
+ if (isa<PHINode>(Op))
+ Builder.SetInsertPoint(BB, BB->getFirstInsertionPt());
+ for (unsigned I = 0; I < Count; ++I)
+--- lib/Transforms/Scalar/SimplifyCFGPass.cpp 2015-01-04 04:03:27.000000000 -0800
++++ lib/Transforms/Scalar/SimplifyCFGPass.cpp 2015-11-28 19:16:00.355459043 -0800
+@@ -96,7 +96,7 @@
+ // single PHI node that is the operand to the return.
+ if (Ret != &BB.front()) {
+ // Check for something else in the block.
+- BasicBlock::iterator I = Ret;
++ BasicBlock::iterator I(Ret);
+ --I;
+ // Skip over debug info.
+ while (isa<DbgInfoIntrinsic>(I) && I != BB.begin())
+@@ -104,7 +104,7 @@
+ if (!isa<DbgInfoIntrinsic>(I) &&
+ (!isa<PHINode>(I) || I != BB.begin() ||
+ Ret->getNumOperands() == 0 ||
+- Ret->getOperand(0) != I))
++ Ret->getOperand(0) != &*I))
+ continue;
+ }
+
+@@ -166,7 +166,7 @@
+ // Loop over all of the basic blocks and remove them if they are unneeded...
+ //
+ for (Function::iterator BBIt = F.begin(); BBIt != F.end(); ) {
+- if (SimplifyCFG(BBIt++, TTI, BonusInstThreshold, DL, AC)) {
++ if (SimplifyCFG(&*BBIt++, TTI, BonusInstThreshold, DL, AC)) {
+ LocalChange = true;
+ ++NumSimpl;
+ }
+--- lib/Transforms/Scalar/Sink.cpp 2014-08-24 16:23:06.000000000 -0700
++++ lib/Transforms/Scalar/Sink.cpp 2015-11-28 19:17:12.178518993 -0800
+@@ -136,7 +136,7 @@
+ bool ProcessedBegin = false;
+ SmallPtrSet<Instruction *, 8> Stores;
+ do {
+- Instruction *Inst = I; // The instruction to sink.
++ Instruction *Inst = &*I; // The instruction to sink.
+
+ // Predecrement I (if it's not begin) so that it isn't invalidated by
+ // sinking.
+@@ -274,6 +274,6 @@
+ dbgs() << ")\n");
+
+ // Move the instruction.
+- Inst->moveBefore(SuccToSinkTo->getFirstInsertionPt());
++ Inst->moveBefore(&*SuccToSinkTo->getFirstInsertionPt());
+ return true;
+ }
+--- lib/Transforms/Scalar/StructurizeCFG.cpp 2014-12-02 20:28:32.000000000 -0800
++++ lib/Transforms/Scalar/StructurizeCFG.cpp 2015-11-28 19:23:41.808228788 -0800
+@@ -842,14 +842,14 @@
+ continue;
+ }
+
+- if (DT->dominates(II, User))
++ if (DT->dominates(&*II, User))
+ continue;
+
+ if (!Initialized) {
+ Value *Undef = UndefValue::get(II->getType());
+ Updater.Initialize(II->getType(), "");
+ Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
+- Updater.AddAvailableValue(BB, II);
++ Updater.AddAvailableValue(BB, &*II);
+ Initialized = true;
+ }
+ Updater.RewriteUseAfterInsertions(U);
+--- lib/Transforms/Scalar/TailRecursionElimination.cpp 2014-11-19 05:32:51.000000000 -0800
++++ lib/Transforms/Scalar/TailRecursionElimination.cpp 2015-11-28 19:32:29.223858053 -0800
+@@ -404,28 +404,22 @@
+ // alloca' is changed from being a static alloca to being a dynamic alloca.
+ // Until this is resolved, disable this transformation if that would ever
+ // happen. This bug is PR962.
+- SmallVector<BasicBlock*, 8> BBToErase;
+- for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
++ for (Function::iterator BBI = F.begin(), E = F.end(); BBI != E;
++ /* inside loop */) {
++ BasicBlock *BB = &*BBI;
++ ++BBI;
++
+ if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB->getTerminator())) {
+ bool Change = ProcessReturningBlock(Ret, OldEntry, TailCallsAreMarkedTail,
+ ArgumentPHIs, !CanTRETailMarkedCall);
+- if (!Change && BB->getFirstNonPHIOrDbg() == Ret) {
++ if (!Change && BB->getFirstNonPHIOrDbg() == Ret)
+ Change = FoldReturnAndProcessPred(BB, Ret, OldEntry,
+ TailCallsAreMarkedTail, ArgumentPHIs,
+ !CanTRETailMarkedCall);
+- // FoldReturnAndProcessPred may have emptied some BB. Remember to
+- // erase them.
+- if (Change && BB->empty())
+- BBToErase.push_back(BB);
+-
+- }
+ MadeChange |= Change;
+ }
+ }
+
+- for (auto BB: BBToErase)
+- BB->eraseFromParent();
+-
+ // If we eliminated any tail recursions, it's possible that we inserted some
+ // silly PHI nodes which just merge an initial value (the incoming operand)
+ // with themselves. Check to see if we did and clean up our mess if so. This
+@@ -588,7 +582,7 @@
+ // Scan backwards from the return, checking to see if there is a tail call in
+ // this block. If so, set CI to it.
+ CallInst *CI = nullptr;
+- BasicBlock::iterator BBI = TI;
++ BasicBlock::iterator BBI(TI);
+ while (true) {
+ CI = dyn_cast<CallInst>(BBI);
+ if (CI && CI->getCalledFunction() == F)
+@@ -609,9 +603,8 @@
+ // and disable this xform in this case, because the code generator will
+ // lower the call to fabs into inline code.
+ if (BB == &F->getEntryBlock() &&
+- FirstNonDbg(BB->front()) == CI &&
+- FirstNonDbg(std::next(BB->begin())) == TI &&
+- CI->getCalledFunction() &&
++ FirstNonDbg(BB->front().getIterator()) == CI &&
++ FirstNonDbg(std::next(BB->begin())) == TI && CI->getCalledFunction() &&
+ !TTI->isLoweredToCall(CI->getCalledFunction())) {
+ // A single-block function with just a call and a return. Check that
+ // the arguments match.
+@@ -650,19 +643,19 @@
+ // tail call if all of the instructions between the call and the return are
+ // movable to above the call itself, leaving the call next to the return.
+ // Check that this is the case now.
+- BasicBlock::iterator BBI = CI;
++ BasicBlock::iterator BBI(CI);
+ for (++BBI; &*BBI != Ret; ++BBI) {
+- if (CanMoveAboveCall(BBI, CI)) continue;
++ if (CanMoveAboveCall(&*BBI, CI)) continue;
+
+ // If we can't move the instruction above the call, it might be because it
+ // is an associative and commutative operation that could be transformed
+ // using accumulator recursion elimination. Check to see if this is the
+ // case, and if so, remember the initial accumulator value for later.
+ if ((AccumulatorRecursionEliminationInitVal =
+- CanTransformAccumulatorRecursion(BBI, CI))) {
++ CanTransformAccumulatorRecursion(&*BBI, CI))) {
+ // Yes, this is accumulator recursion. Remember which instruction
+ // accumulates.
+- AccumulatorRecursionInstr = BBI;
++ AccumulatorRecursionInstr = &*BBI;
+ } else {
+ return false; // Otherwise, we cannot eliminate the tail recursion!
+ }
+@@ -712,19 +705,19 @@
+ NEBI = NewEntry->begin(); OEBI != E; )
+ if (AllocaInst *AI = dyn_cast<AllocaInst>(OEBI++))
+ if (isa<ConstantInt>(AI->getArraySize()))
+- AI->moveBefore(NEBI);
++ AI->moveBefore(&*NEBI);
+
+ // Now that we have created a new block, which jumps to the entry
+ // block, insert a PHI node for each argument of the function.
+ // For now, we initialize each PHI to only have the real arguments
+ // which are passed in.
+- Instruction *InsertPos = OldEntry->begin();
++ Instruction *InsertPos = &OldEntry->front();
+ for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
+ I != E; ++I) {
+ PHINode *PN = PHINode::Create(I->getType(), 2,
+ I->getName() + ".tr", InsertPos);
+ I->replaceAllUsesWith(PN); // Everyone use the PHI node now!
+- PN->addIncoming(I, NewEntry);
++ PN->addIncoming(&*I, NewEntry);
+ ArgumentPHIs.push_back(PN);
+ }
+ }
+@@ -753,10 +746,9 @@
+ Instruction *AccRecInstr = AccumulatorRecursionInstr;
+ // Start by inserting a new PHI node for the accumulator.
+ pred_iterator PB = pred_begin(OldEntry), PE = pred_end(OldEntry);
+- PHINode *AccPN =
+- PHINode::Create(AccumulatorRecursionEliminationInitVal->getType(),
+- std::distance(PB, PE) + 1,
+- "accumulator.tr", OldEntry->begin());
++ PHINode *AccPN = PHINode::Create(
++ AccumulatorRecursionEliminationInitVal->getType(),
++ std::distance(PB, PE) + 1, "accumulator.tr", &OldEntry->front());
+
+ // Loop over all of the predecessors of the tail recursion block. For the
+ // real entry into the function we seed the PHI with the initial value,
+--- lib/Transforms/Utils/AddDiscriminators.cpp 2014-12-09 10:38:53.000000000 -0800
++++ lib/Transforms/Utils/AddDiscriminators.cpp 2015-11-29 09:01:43.033905645 -0800
+@@ -172,7 +172,7 @@
+ // Traverse all the blocks looking for instructions in different
+ // blocks that are at the same file:line location.
+ for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
+- BasicBlock *B = I;
++ BasicBlock *B = &*I;
+ TerminatorInst *Last = B->getTerminator();
+ DebugLoc LastLoc = Last->getDebugLoc();
+ if (LastLoc.isUnknown()) continue;
+--- lib/Transforms/Utils/BasicBlockUtils.cpp 2014-11-18 16:17:31.000000000 -0800
++++ lib/Transforms/Utils/BasicBlockUtils.cpp 2015-11-29 09:05:35.763274502 -0800
+@@ -255,7 +255,7 @@
+ // block.
+ assert(SP == BB && "CFG broken");
+ SP = nullptr;
+- return SplitBlock(Succ, Succ->begin(), P);
++ return SplitBlock(Succ, &Succ->front(), P);
+ }
+
+ // Otherwise, if BB has a single successor, split it at the bottom of the
+@@ -283,7 +283,7 @@
+ /// the loop info is updated.
+ ///
+ BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
+- BasicBlock::iterator SplitIt = SplitPt;
++ BasicBlock::iterator SplitIt = SplitPt->getIterator();
+ while (isa<PHINode>(SplitIt) || isa<LandingPadInst>(SplitIt))
+ ++SplitIt;
+ BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
+@@ -642,7 +642,7 @@
+ // return instruction.
+ V = BCI->getOperand(0);
+ NewBC = BCI->clone();
+- Pred->getInstList().insert(NewRet, NewBC);
++ Pred->getInstList().insert(NewRet->getIterator(), NewBC);
+ *i = NewBC;
+ }
+ if (PHINode *PN = dyn_cast<PHINode>(V)) {
+@@ -688,7 +688,7 @@
+ MDNode *BranchWeights,
+ DominatorTree *DT) {
+ BasicBlock *Head = SplitBefore->getParent();
+- BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
++ BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
+ TerminatorInst *HeadOldTerm = Head->getTerminator();
+ LLVMContext &C = Head->getContext();
+ BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
+@@ -739,7 +739,7 @@
+ TerminatorInst **ElseTerm,
+ MDNode *BranchWeights) {
+ BasicBlock *Head = SplitBefore->getParent();
+- BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
++ BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
+ TerminatorInst *HeadOldTerm = Head->getTerminator();
+ LLVMContext &C = Head->getContext();
+ BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
+--- lib/Transforms/Utils/BreakCriticalEdges.cpp 2014-11-18 16:17:31.000000000 -0800
++++ lib/Transforms/Utils/BreakCriticalEdges.cpp 2015-11-29 09:07:57.703524612 -0800
+@@ -98,7 +98,7 @@
+ PHINode *NewPN =
+ PHINode::Create(PN->getType(), Preds.size(), "split",
+ SplitBB->isLandingPad() ?
+- SplitBB->begin() : SplitBB->getTerminator());
++ &SplitBB->front() : SplitBB->getTerminator());
+ for (unsigned i = 0, e = Preds.size(); i != e; ++i)
+ NewPN->addIncoming(V, Preds[i]);
+
+@@ -152,7 +152,7 @@
+
+ // Insert the block into the function... right after the block TI lives in.
+ Function &F = *TIBB->getParent();
+- Function::iterator FBBI = TIBB;
++ Function::iterator FBBI = TIBB->getIterator();
+ F.getBasicBlockList().insert(++FBBI, NewBB);
+
+ // If there are any PHI nodes in DestBB, we need to update them so that they
+--- lib/Transforms/Utils/BypassSlowDivision.cpp 2014-04-24 22:29:35.000000000 -0700
++++ lib/Transforms/Utils/BypassSlowDivision.cpp 2015-11-29 09:10:30.545799550 -0800
+@@ -82,7 +82,7 @@
+ bool UseSignedOp,
+ DivCacheTy &PerBBDivCache) {
+ // Get instruction operands
+- Instruction *Instr = J;
++ Instruction *Instr = &*J;
+ Value *Dividend = Instr->getOperand(0);
+ Value *Divisor = Instr->getOperand(1);
+
+@@ -94,7 +94,7 @@
+ }
+
+ // Basic Block is split before divide
+- BasicBlock *MainBB = I;
++ BasicBlock *MainBB = &*I;
+ BasicBlock *SuccessorBB = I->splitBasicBlock(J);
+ ++I; //advance iterator I to successorBB
+
+@@ -190,7 +190,7 @@
+ bool UseSignedOp,
+ DivCacheTy &PerBBDivCache) {
+ // Get instruction operands
+- Instruction *Instr = J;
++ Instruction *Instr = &*J;
+ DivOpInfo Key(UseSignedOp, Instr->getOperand(0), Instr->getOperand(1));
+ DivCacheTy::iterator CacheI = PerBBDivCache.find(Key);
+
+--- lib/Transforms/Utils/CloneFunction.cpp 2014-12-18 22:06:18.000000000 -0800
++++ lib/Transforms/Utils/CloneFunction.cpp 2015-11-29 09:27:19.893077178 -0800
+@@ -51,7 +51,7 @@
+ if (II->hasName())
+ NewInst->setName(II->getName()+NameSuffix);
+ NewBB->getInstList().push_back(NewInst);
+- VMap[II] = NewInst; // Add instruction map to value.
++ VMap[&*II] = NewInst; // Add instruction map to value.
+
+ hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
+ if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
+@@ -86,7 +86,7 @@
+ #ifndef NDEBUG
+ for (Function::const_arg_iterator I = OldFunc->arg_begin(),
+ E = OldFunc->arg_end(); I != E; ++I)
+- assert(VMap.count(I) && "No mapping from source argument specified!");
++ assert(VMap.count(&*I) && "No mapping from source argument specified!");
+ #endif
+
+ // Copy all attributes other than those stored in the AttributeSet. We need
+@@ -145,11 +145,12 @@
+
+ // Loop over all of the instructions in the function, fixing up operand
+ // references as we go. This uses VMap to do all the hard work.
+- for (Function::iterator BB = cast<BasicBlock>(VMap[OldFunc->begin()]),
+- BE = NewFunc->end(); BB != BE; ++BB)
++ for (Function::iterator BB =
++ cast<BasicBlock>(VMap[&OldFunc->front()])->getIterator(),
++ BE = NewFunc->end(); BB != BE; ++BB)
+ // Loop over all instructions, fixing each one as we find it...
+- for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II)
+- RemapInstruction(II, VMap,
++ for (Instruction &II : *BB)
++ RemapInstruction(&II, VMap,
+ ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
+ TypeMapper, Materializer);
+ }
+@@ -220,7 +221,7 @@
+ //
+ for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
+ I != E; ++I)
+- if (VMap.count(I) == 0) // Haven't mapped the argument to anything yet?
++ if (VMap.count(&*I) == 0) // Haven't mapped the argument to anything yet?
+ ArgTypes.push_back(I->getType());
+
+ // Create a new function type...
+@@ -234,9 +235,9 @@
+ Function::arg_iterator DestI = NewF->arg_begin();
+ for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
+ I != E; ++I)
+- if (VMap.count(I) == 0) { // Is this argument preserved?
+- DestI->setName(I->getName()); // Copy the name over...
+- VMap[I] = DestI++; // Add mapping to VMap
++ if (VMap.count(&*I) == 0) { // Is this argument preserved?
++ DestI->setName(I->getName()); // Copy the name over...
++ VMap[&*I] = &*DestI++; // Add mapping to VMap
+ }
+
+ if (ModuleLevelChanges)
+@@ -332,7 +333,7 @@
+ if (Value *MappedV = VMap.lookup(V))
+ V = MappedV;
+
+- VMap[II] = V;
++ VMap[&*II] = V;
+ delete NewInst;
+ continue;
+ }
+@@ -340,9 +341,10 @@
+
+ if (II->hasName())
+ NewInst->setName(II->getName()+NameSuffix);
+- VMap[II] = NewInst; // Add instruction map to value.
++ VMap[&*II] = NewInst; // Add instruction map to value.
+ NewBB->getInstList().push_back(NewInst);
+ hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
++
+ if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
+ if (isa<ConstantInt>(AI->getArraySize()))
+ hasStaticAllocas = true;
+@@ -429,7 +431,7 @@
+ #ifndef NDEBUG
+ for (Function::const_arg_iterator II = OldFunc->arg_begin(),
+ E = OldFunc->arg_end(); II != E; ++II)
+- assert(VMap.count(II) && "No mapping from source argument specified!");
++ assert(VMap.count(&*II) && "No mapping from source argument specified!");
+ #endif
+
+ PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
+@@ -452,7 +454,7 @@
+ SmallVector<const PHINode*, 16> PHIToResolve;
+ for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
+ BI != BE; ++BI) {
+- Value *V = VMap[BI];
++ Value *V = VMap[&*BI];
+ BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
+ if (!NewBB) continue; // Dead block.
+
+@@ -546,8 +548,8 @@
+ while ((PN = dyn_cast<PHINode>(I++))) {
+ Value *NV = UndefValue::get(PN->getType());
+ PN->replaceAllUsesWith(NV);
+- assert(VMap[OldI] == PN && "VMap mismatch");
+- VMap[OldI] = NV;
++ assert(VMap[&*OldI] == PN && "VMap mismatch");
++ VMap[&*OldI] = NV;
+ PN->eraseFromParent();
+ ++OldI;
+ }
+@@ -569,15 +571,16 @@
+ // and zap unconditional fall-through branches. This happen all the time when
+ // specializing code: code specialization turns conditional branches into
+ // uncond branches, and this code folds them.
+- Function::iterator Begin = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]);
++ Function::iterator Begin =
++ cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()])->getIterator();
+ Function::iterator I = Begin;
+ while (I != NewFunc->end()) {
+ // Check if this block has become dead during inlining or other
+ // simplifications. Note that the first block will appear dead, as it has
+ // not yet been wired up properly.
+- if (I != Begin && (pred_begin(I) == pred_end(I) ||
+- I->getSinglePredecessor() == I)) {
+- BasicBlock *DeadBB = I++;
++ if ((I != Begin) && (pred_begin(&*I) == pred_end(&*I) ||
++ I->getSinglePredecessor() == &*I)) {
++ BasicBlock *DeadBB = &*I++;
+ DeleteDeadBlock(DeadBB);
+ continue;
+ }
+@@ -587,7 +590,7 @@
+ // simplification required looking through PHI nodes, those are only
+ // available after forming the full basic block. That may leave some here,
+ // and we still want to prune the dead code as early as possible.
+- ConstantFoldTerminator(I);
++ ConstantFoldTerminator(&*I);
+
+ BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
+ if (!BI || BI->isConditional()) { ++I; continue; }
+@@ -606,7 +609,7 @@
+ BI->eraseFromParent();
+
+ // Make all PHI nodes that referred to Dest now refer to I as their source.
+- Dest->replaceAllUsesWith(I);
++ Dest->replaceAllUsesWith(&*I);
+
+ // Move all the instructions in the succ to the pred.
+ I->getInstList().splice(I->end(), Dest->getInstList());
+@@ -620,9 +623,9 @@
+ // Make a final pass over the basic blocks from theh old function to gather
+ // any return instructions which survived folding. We have to do this here
+ // because we can iteratively remove and merge returns above.
+- for (Function::iterator I = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]),
+- E = NewFunc->end();
+- I != E; ++I)
++ for (Function::iterator I =
++ cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()])->getIterator(),
++ E = NewFunc->end(); I != E; ++I)
+ if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
+ Returns.push_back(RI);
+ }
+--- lib/Transforms/Utils/CloneModule.cpp 2014-12-23 00:23:45.000000000 -0800
++++ lib/Transforms/Utils/CloneModule.cpp 2015-11-29 10:05:42.438731638 -0800
+@@ -45,15 +45,15 @@
+ //
+ for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
+ I != E; ++I) {
+- GlobalVariable *GV = new GlobalVariable(*New,
++ GlobalVariable *GV = new GlobalVariable(*New,
+ I->getType()->getElementType(),
+ I->isConstant(), I->getLinkage(),
+ (Constant*) nullptr, I->getName(),
+ (GlobalVariable*) nullptr,
+ I->getThreadLocalMode(),
+ I->getType()->getAddressSpace());
+- GV->copyAttributesFrom(I);
+- VMap[I] = GV;
++ GV->copyAttributesFrom(&*I);
++ VMap[&*I] = GV;
+ }
+
+ // Loop over the functions in the module, making external functions as before
+@@ -61,8 +61,8 @@
+ Function *NF =
+ Function::Create(cast<FunctionType>(I->getType()->getElementType()),
+ I->getLinkage(), I->getName(), New);
+- NF->copyAttributesFrom(I);
+- VMap[I] = NF;
++ NF->copyAttributesFrom(&*I);
++ VMap[&*I] = NF;
+ }
+
+ // Loop over the aliases in the module
+@@ -72,8 +72,8 @@
+ auto *GA =
+ GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
+ I->getLinkage(), I->getName(), New);
+- GA->copyAttributesFrom(I);
+- VMap[I] = GA;
++ GA->copyAttributesFrom(&*I);
++ VMap[&*I] = GA;
+ }
+
+ // Now that all of the things that global variable initializer can refer to
+@@ -82,7 +82,7 @@
+ //
+ for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
+ I != E; ++I) {
+- GlobalVariable *GV = cast<GlobalVariable>(VMap[I]);
++ GlobalVariable *GV = cast<GlobalVariable>(VMap[&*I]);
+ if (I->hasInitializer())
+ GV->setInitializer(MapValue(I->getInitializer(), VMap));
+ }
+@@ -90,24 +90,24 @@
+ // Similarly, copy over function bodies now...
+ //
+ for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
+- Function *F = cast<Function>(VMap[I]);
++ Function *F = cast<Function>(VMap[&*I]);
+ if (!I->isDeclaration()) {
+ Function::arg_iterator DestI = F->arg_begin();
+ for (Function::const_arg_iterator J = I->arg_begin(); J != I->arg_end();
+ ++J) {
+ DestI->setName(J->getName());
+- VMap[J] = DestI++;
++ VMap[&*J] = &*DestI++;
+ }
+
+ SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned.
+- CloneFunctionInto(F, I, VMap, /*ModuleLevelChanges=*/true, Returns);
++ CloneFunctionInto(F, &*I, VMap, /*ModuleLevelChanges=*/true, Returns);
+ }
+ }
+
+ // And aliases
+ for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
+ I != E; ++I) {
+- GlobalAlias *GA = cast<GlobalAlias>(VMap[I]);
++ GlobalAlias *GA = cast<GlobalAlias>(VMap[&*I]);
+ if (const Constant *C = I->getAliasee())
+ GA->setAliasee(MapValue(C, VMap));
+ }
+--- lib/Transforms/Utils/CodeExtractor.cpp 2014-07-21 10:06:51.000000000 -0700
++++ lib/Transforms/Utils/CodeExtractor.cpp 2015-11-29 10:25:40.506775548 -0800
+@@ -175,7 +175,7 @@
+
+ for (User *U : II->users())
+ if (!definedInRegion(Blocks, U)) {
+- Outputs.insert(II);
++ Outputs.insert(&*II);
+ break;
+ }
+ }
+@@ -211,7 +211,7 @@
+ // containing PHI nodes merging values from outside of the region, and a
+ // second that contains all of the code for the block and merges back any
+ // incoming values from inside of the region.
+- BasicBlock::iterator AfterPHIs = Header->getFirstNonPHI();
++ BasicBlock::iterator AfterPHIs = Header->getFirstNonPHI()->getIterator();
+ BasicBlock *NewBB = Header->splitBasicBlock(AfterPHIs,
+ Header->getName()+".ce");
+
+@@ -246,7 +246,7 @@
+ // Create a new PHI node in the new region, which has an incoming value
+ // from OldPred of PN.
+ PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
+- PN->getName()+".ce", NewBB->begin());
++ PN->getName()+".ce", &NewBB->front());
+ NewPN->addIncoming(PN, OldPred);
+
+ // Loop over all of the incoming value in PN, moving them to NewPN if they
+@@ -266,14 +266,15 @@
+ for (SetVector<BasicBlock *>::iterator I = Blocks.begin(), E = Blocks.end();
+ I != E; ++I)
+ if (ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator())) {
+- BasicBlock *New = (*I)->splitBasicBlock(RI, (*I)->getName()+".ret");
++ BasicBlock *New =
++ (*I)->splitBasicBlock(RI->getIterator(), (*I)->getName() + ".ret");
+ if (DT) {
+ // Old dominates New. New node dominates all other nodes dominated
+ // by Old.
+ DomTreeNode *OldNode = DT->getNode(*I);
+ SmallVector<DomTreeNode*, 8> Children;
+ for (DomTreeNode::iterator DI = OldNode->begin(), DE = OldNode->end();
+- DI != DE; ++DI)
++ DI != DE; ++DI)
+ Children.push_back(*DI);
+
+ DomTreeNode *NewNode = DT->addNewBlock(New, *I);
+@@ -364,11 +365,11 @@
+ Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
+ Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
+ TerminatorInst *TI = newFunction->begin()->getTerminator();
+- GetElementPtrInst *GEP =
+- GetElementPtrInst::Create(AI, Idx, "gep_" + inputs[i]->getName(), TI);
++ GetElementPtrInst *GEP =
++ GetElementPtrInst::Create(&*AI, Idx, "gep_" + inputs[i]->getName(), TI);
+ RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
+ } else
+- RewriteVal = AI++;
++ RewriteVal = &*AI++;
+
+ std::vector<User*> Users(inputs[i]->user_begin(), inputs[i]->user_end());
+ for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end();
+@@ -441,7 +442,7 @@
+ } else {
+ AllocaInst *alloca =
+ new AllocaInst((*i)->getType(), nullptr, (*i)->getName()+".loc",
+- codeReplacer->getParent()->begin()->begin());
++ &codeReplacer->getParent()->front().front());
+ ReloadOutputs.push_back(alloca);
+ params.push_back(alloca);
+ }
+@@ -458,7 +459,7 @@
+ Type *StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
+ Struct =
+ new AllocaInst(StructArgTy, nullptr, "structArg",
+- codeReplacer->getParent()->begin()->begin());
++ &codeReplacer->getParent()->front().front());
+ params.push_back(Struct);
+
+ for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
+@@ -607,12 +608,12 @@
+ Idx[1] = ConstantInt::get(Type::getInt32Ty(Context),
+ FirstOut+out);
+ GetElementPtrInst *GEP =
+- GetElementPtrInst::Create(OAI, Idx,
++ GetElementPtrInst::Create(&*OAI, Idx,
+ "gep_" + outputs[out]->getName(),
+ NTRet);
+ new StoreInst(outputs[out], GEP, NTRet);
+ } else {
+- new StoreInst(outputs[out], OAI, NTRet);
++ new StoreInst(outputs[out], &*OAI, NTRet);
+ }
+ }
+ // Advance output iterator even if we don't emit a store
+--- lib/Transforms/Utils/CtorUtils.cpp 2014-09-23 15:33:01.000000000 -0700
++++ lib/Transforms/Utils/CtorUtils.cpp 2015-11-29 10:27:14.531198062 -0800
+@@ -49,7 +49,7 @@
+ GlobalVariable *NGV =
+ new GlobalVariable(CA->getType(), GCL->isConstant(), GCL->getLinkage(),
+ CA, "", GCL->getThreadLocalMode());
+- GCL->getParent()->getGlobalList().insert(GCL, NGV);
++ GCL->getParent()->getGlobalList().insert(GCL->getIterator(), NGV);
+ NGV->takeName(GCL);
+
+ // Nuke the old list, replacing any uses with the new one.
+--- lib/Transforms/Utils/DemoteRegToStack.cpp 2014-04-24 22:29:35.000000000 -0700
++++ lib/Transforms/Utils/DemoteRegToStack.cpp 2015-11-29 10:33:53.846940110 -0800
+@@ -36,7 +36,7 @@
+ } else {
+ Function *F = I.getParent()->getParent();
+ Slot = new AllocaInst(I.getType(), nullptr, I.getName()+".reg2mem",
+- F->getEntryBlock().begin());
++ &F->getEntryBlock().front());
+ }
+
+ // Change all of the users of the instruction to read from the stack slot.
+@@ -77,30 +77,15 @@
+ // AFTER the terminator instruction.
+ BasicBlock::iterator InsertPt;
+ if (!isa<TerminatorInst>(I)) {
+- InsertPt = &I;
+- ++InsertPt;
++ InsertPt = ++I.getIterator();
++ for (; isa<PHINode>(InsertPt) || isa<LandingPadInst>(InsertPt);
++ ++InsertPt);
+ } else {
+ InvokeInst &II = cast<InvokeInst>(I);
+- if (II.getNormalDest()->getSinglePredecessor())
+- InsertPt = II.getNormalDest()->getFirstInsertionPt();
+- else {
+- // We cannot demote invoke instructions to the stack if their normal edge
+- // is critical. Therefore, split the critical edge and insert the store
+- // in the newly created basic block.
+- unsigned SuccNum = GetSuccessorNumber(I.getParent(), II.getNormalDest());
+- TerminatorInst *TI = &cast<TerminatorInst>(I);
+- assert (isCriticalEdge(TI, SuccNum) &&
+- "Expected a critical edge!");
+- BasicBlock *BB = SplitCriticalEdge(TI, SuccNum);
+- assert (BB && "Unable to split critical edge.");
+- InsertPt = BB->getFirstInsertionPt();
+- }
++ InsertPt = II.getNormalDest()->getFirstInsertionPt();
+ }
+
+- for (; isa<PHINode>(InsertPt) || isa<LandingPadInst>(InsertPt); ++InsertPt)
+- /* empty */; // Don't insert before PHI nodes or landingpad instrs.
+-
+- new StoreInst(&I, Slot, InsertPt);
++ new StoreInst(&I, Slot, &*InsertPt);
+ return Slot;
+ }
+
+@@ -121,7 +106,7 @@
+ } else {
+ Function *F = P->getParent()->getParent();
+ Slot = new AllocaInst(P->getType(), nullptr, P->getName()+".reg2mem",
+- F->getEntryBlock().begin());
++ &F->getEntryBlock().front());
+ }
+
+ // Iterate over each operand inserting a store in each predecessor.
+@@ -135,12 +120,12 @@
+ }
+
+ // Insert a load in place of the PHI and replace all uses.
+- BasicBlock::iterator InsertPt = P;
++ BasicBlock::iterator InsertPt = P->getIterator();
+
+ for (; isa<PHINode>(InsertPt) || isa<LandingPadInst>(InsertPt); ++InsertPt)
+ /* empty */; // Don't insert before PHI nodes or landingpad instrs.
+
+- Value *V = new LoadInst(Slot, P->getName()+".reload", InsertPt);
++ Value *V = new LoadInst(Slot, P->getName()+".reload", &*InsertPt);
+ P->replaceAllUsesWith(V);
+
+ // Delete PHI.
+--- lib/Transforms/Utils/FlattenCFG.cpp 2014-08-13 13:31:53.000000000 -0700
++++ lib/Transforms/Utils/FlattenCFG.cpp 2015-11-29 10:42:20.827355223 -0800
+@@ -177,8 +177,9 @@
+
+ // Instructions in the internal condition blocks should be safe
+ // to hoist up.
+- for (BasicBlock::iterator BI = Pred->begin(), BE = PBI; BI != BE;) {
+- Instruction *CI = BI++;
++ for (BasicBlock::iterator BI = Pred->begin(), BE = PBI->getIterator();
++ BI != BE;) {
++ Instruction *CI = &*BI++;
+ if (isa<PHINode>(CI) || !isSafeToSpeculativelyExecute(CI))
+ return false;
+ }
+@@ -315,7 +316,7 @@
+ BasicBlock *Block1,
+ BasicBlock *Block2) {
+ TerminatorInst *PTI2 = Head2->getTerminator();
+- Instruction *PBI2 = Head2->begin();
++ Instruction *PBI2 = &Head2->front();
+
+ bool eq1 = (Block1 == Head1);
+ bool eq2 = (Block2 == Head2);
+@@ -327,9 +328,9 @@
+ // Check whether instructions in Block1 and Block2 are identical
+ // and do not alias with instructions in Head2.
+ BasicBlock::iterator iter1 = Block1->begin();
+- BasicBlock::iterator end1 = Block1->getTerminator();
++ BasicBlock::iterator end1 = Block1->getTerminator()->getIterator();
+ BasicBlock::iterator iter2 = Block2->begin();
+- BasicBlock::iterator end2 = Block2->getTerminator();
++ BasicBlock::iterator end2 = Block2->getTerminator()->getIterator();
+
+ while (1) {
+ if (iter1 == end1) {
+@@ -338,7 +339,7 @@
+ break;
+ }
+
+- if (!iter1->isIdenticalTo(iter2))
++ if (!iter1->isIdenticalTo(&*iter2))
+ return false;
+
+ // Illegal to remove instructions with side effects except
+@@ -356,10 +357,10 @@
+ return false;
+
+ if (iter1->mayWriteToMemory()) {
+- for (BasicBlock::iterator BI = PBI2, BE = PTI2; BI != BE; ++BI) {
++ for (BasicBlock::iterator BI(PBI2), BE(PTI2); BI != BE; ++BI) {
+ if (BI->mayReadFromMemory() || BI->mayWriteToMemory()) {
+ // Check alias with Head2.
+- if (!AA || AA->alias(iter1, BI))
++ if (!AA || AA->alias(&*iter1, &*BI))
+ return false;
+ }
+ }
+@@ -413,7 +414,7 @@
+ return false;
+
+ TerminatorInst *PTI2 = SecondEntryBlock->getTerminator();
+- Instruction *PBI2 = SecondEntryBlock->begin();
++ Instruction *PBI2 = &SecondEntryBlock->front();
+
+ if (!CompareIfRegionBlock(FirstEntryBlock, SecondEntryBlock, IfTrue1,
+ IfTrue2))
+@@ -425,8 +426,8 @@
+
+ // Check whether \param SecondEntryBlock has side-effect and is safe to
+ // speculate.
+- for (BasicBlock::iterator BI = PBI2, BE = PTI2; BI != BE; ++BI) {
+- Instruction *CI = BI;
++ for (BasicBlock::iterator BI(PBI2), BE(PTI2); BI != BE; ++BI) {
++ Instruction *CI = &*BI;
+ if (isa<PHINode>(CI) || CI->mayHaveSideEffects() ||
+ !isSafeToSpeculativelyExecute(CI))
+ return false;
+--- lib/Transforms/Utils/InlineFunction.cpp 2015-01-04 04:03:27.000000000 -0800
++++ lib/Transforms/Utils/InlineFunction.cpp 2015-11-29 12:31:32.233733995 -0800
+@@ -128,7 +128,7 @@
+ if (InnerResumeDest) return InnerResumeDest;
+
+ // Split the landing pad.
+- BasicBlock::iterator SplitPoint = CallerLPad; ++SplitPoint;
++ BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator();
+ InnerResumeDest =
+ OuterResumeDest->splitBasicBlock(SplitPoint,
+ OuterResumeDest->getName() + ".body");
+@@ -137,7 +137,7 @@
+ const unsigned PHICapacity = 2;
+
+ // Create corresponding new PHIs for all the PHIs in the outer landing pad.
+- BasicBlock::iterator InsertPoint = InnerResumeDest->begin();
++ Instruction *InsertPoint = &InnerResumeDest->front();
+ BasicBlock::iterator I = OuterResumeDest->begin();
+ for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
+ PHINode *OuterPHI = cast<PHINode>(I);
+@@ -185,7 +185,8 @@
+ static void HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
+ InvokeInliningInfo &Invoke) {
+ for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
+- Instruction *I = BBI++;
++ Instruction *I = &*BBI;
++ ++BBI;
+
+ // We only need to check for function calls: inlined invoke
+ // instructions require no special handling.
+@@ -198,7 +199,8 @@
+
+ // Convert this function call into an invoke instruction. First, split the
+ // basic block.
+- BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
++ BasicBlock *Split =
++ BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc");
+
+ // Delete the unconditional branch inserted by splitBasicBlock
+ BB->getInstList().pop_back();
+@@ -246,7 +248,8 @@
+
+ // Get all of the inlined landing pad instructions.
+ SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
+- for (Function::iterator I = FirstNewBlock, E = Caller->end(); I != E; ++I)
++ for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end();
++ I != E; ++I)
+ if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
+ InlinedLPads.insert(II->getLandingPadInst());
+
+@@ -262,9 +265,10 @@
+ InlinedLPad->setCleanup(true);
+ }
+
+- for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB){
++ for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
++ BB != E; ++BB){
+ if (InlinedCodeInfo.ContainsCalls)
+- HandleCallsInBlockInlinedThroughInvoke(BB, Invoke);
++ HandleCallsInBlockInlinedThroughInvoke(&*BB, Invoke);
+
+ // Forward any resumes that are remaining here.
+ if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
+@@ -406,10 +410,9 @@
+ const Function *CalledFunc = CS.getCalledFunction();
+ SmallVector<const Argument *, 4> NoAliasArgs;
+
+- for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
+- E = CalledFunc->arg_end(); I != E; ++I) {
+- if (I->hasNoAliasAttr() && !I->hasNUses(0))
+- NoAliasArgs.push_back(I);
++ for (const Argument &A : CalledFunc->args()) {
++ if (A.hasNoAliasAttr() && !A.hasNUses(0))
++ NoAliasArgs.push_back(&A);
+ }
+
+ if (NoAliasArgs.empty())
+@@ -727,7 +730,7 @@
+ BasicBlock *InsertBlock,
+ InlineFunctionInfo &IFI) {
+ Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
+- IRBuilder<> Builder(InsertBlock->begin());
++ IRBuilder<> Builder(InsertBlock, InsertBlock->begin());
+
+ Value *Size;
+ if (IFI.DL == nullptr)
+@@ -962,7 +965,7 @@
+
+ // Get an iterator to the last basic block in the function, which will have
+ // the new function inlined after it.
+- Function::iterator LastBlock = &Caller->back();
++ Function::iterator LastBlock = --Caller->end();
+
+ // Make sure to capture all of the return instructions from the cloned
+ // function.
+@@ -997,7 +1000,7 @@
+ ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
+ }
+
+- VMap[I] = ActualArg;
++ VMap[&*I] = ActualArg;
+ }
+
+ // Add alignment assumptions if necessary. We do this before the inlined
+@@ -1014,12 +1017,13 @@
+ &InlinedFunctionInfo, IFI.DL, TheCall);
+
+ // Remember the first block that is newly cloned over.
+- FirstNewBlock = LastBlock; ++FirstNewBlock;
++ FirstNewBlock = LastBlock;
++ ++FirstNewBlock;
+
+ // Inject byval arguments initialization.
+ for (std::pair<Value*, Value*> &Init : ByValInit)
+ HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
+- FirstNewBlock, IFI);
++ &*FirstNewBlock, IFI);
+
+ // Update the callgraph if requested.
+ if (IFI.CG)
+@@ -1077,7 +1081,7 @@
+ // reinserted.
+ Caller->getEntryBlock().getInstList().splice(InsertPoint,
+ FirstNewBlock->getInstList(),
+- AI, I);
++ AI->getIterator(), I);
+ }
+ }
+
+@@ -1123,7 +1127,7 @@
+ // Leave lifetime markers for the static alloca's, scoping them to the
+ // function we just inlined.
+ if (InsertLifetime && !IFI.StaticAllocas.empty()) {
+- IRBuilder<> builder(FirstNewBlock->begin());
++ IRBuilder<> builder(&FirstNewBlock->front());
+ for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
+ AllocaInst *AI = IFI.StaticAllocas[ai];
+
+@@ -1172,8 +1176,9 @@
+ Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
+
+ // Insert the llvm.stacksave.
+- CallInst *SavedPtr = IRBuilder<>(FirstNewBlock, FirstNewBlock->begin())
+- .CreateCall(StackSave, "savedstack");
++ CallInst *SavedPtr =
++ IRBuilder<>(&*FirstNewBlock,
++ FirstNewBlock->begin()).CreateCall(StackSave, "savedstack");
+
+ // Insert a call to llvm.stackrestore before any return instructions in the
+ // inlined function.
+@@ -1189,7 +1194,7 @@
+ // If we are inlining for an invoke instruction, we must make sure to rewrite
+ // any call instructions into invoke instructions.
+ if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
+- HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
++ HandleInlinedInvoke(II, &*FirstNewBlock, InlinedFunctionInfo);
+
+ // Handle any inlined musttail call sites. In order for a new call site to be
+ // musttail, the source of the clone and the inlined call site must have been
+@@ -1233,8 +1238,10 @@
+ // the calling basic block.
+ if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
+ // Move all of the instructions right before the call.
+- OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
+- FirstNewBlock->begin(), FirstNewBlock->end());
++ OrigBB->getInstList().splice(TheCall->getIterator(),
++ FirstNewBlock->getInstList(),
++ FirstNewBlock->begin(),
++ FirstNewBlock->end());
+ // Remove the cloned basic block.
+ Caller->getBasicBlockList().pop_back();
+
+@@ -1280,14 +1287,15 @@
+ // Split the basic block. This guarantees that no PHI nodes will have to be
+ // updated due to new incoming edges, and make the invoke case more
+ // symmetric to the call case.
+- AfterCallBB = OrigBB->splitBasicBlock(CreatedBranchToNormalDest,
+- CalledFunc->getName()+".exit");
++ AfterCallBB =
++ OrigBB->splitBasicBlock(CreatedBranchToNormalDest->getIterator(),
++ CalledFunc->getName() + ".exit");
+
+ } else { // It's a call
+ // If this is a call instruction, we need to split the basic block that
+ // the call lives in.
+ //
+- AfterCallBB = OrigBB->splitBasicBlock(TheCall,
++ AfterCallBB = OrigBB->splitBasicBlock(TheCall->getIterator(),
+ CalledFunc->getName()+".exit");
+ }
+
+@@ -1297,13 +1305,14 @@
+ TerminatorInst *Br = OrigBB->getTerminator();
+ assert(Br && Br->getOpcode() == Instruction::Br &&
+ "splitBasicBlock broken!");
+- Br->setOperand(0, FirstNewBlock);
++ Br->setOperand(0, &*FirstNewBlock);
+
+
+ // Now that the function is correct, make it a little bit nicer. In
+ // particular, move the basic blocks inserted from the end of the function
+ // into the space made by splitting the source basic block.
+- Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
++ Caller->getBasicBlockList().splice(AfterCallBB->getIterator(),
++ Caller->getBasicBlockList(),
+ FirstNewBlock, Caller->end());
+
+ // Handle all of the return instructions that we just cloned in, and eliminate
+@@ -1316,7 +1325,7 @@
+ // possible incoming values.
+ if (!TheCall->use_empty()) {
+ PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
+- AfterCallBB->begin());
++ &AfterCallBB->front());
+ // Anything that used the result of the function call should now use the
+ // PHI node as their operand.
+ TheCall->replaceAllUsesWith(PHI);
+@@ -1396,7 +1405,7 @@
+ // Splice the code entry block into calling block, right before the
+ // unconditional branch.
+ CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
+- OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
++ OrigBB->getInstList().splice(Br->getIterator(), CalleeEntry->getInstList());
+
+ // Remove the unconditional branch.
+ OrigBB->getInstList().erase(Br);
+--- lib/Transforms/Utils/IntegerDivision.cpp 2014-11-05 13:28:24.000000000 -0800
++++ lib/Transforms/Utils/IntegerDivision.cpp 2015-11-29 12:34:15.372349168 -0800
+@@ -401,7 +401,7 @@
+ // If we didn't actually generate an urem instruction, we're done
+ // This happens for example if the input were constant. In this case the
+ // Builder insertion point was unchanged
+- if (Rem == Builder.GetInsertPoint())
++ if (Rem == Builder.GetInsertPoint().getNodePtrUnchecked())
+ return true;
+
+ BinaryOperator *BO = dyn_cast<BinaryOperator>(Builder.GetInsertPoint());
+@@ -461,7 +461,7 @@
+ // If we didn't actually generate an udiv instruction, we're done
+ // This happens for example if the input were constant. In this case the
+ // Builder insertion point was unchanged
+- if (Div == Builder.GetInsertPoint())
++ if (Div == Builder.GetInsertPoint().getNodePtrUnchecked())
+ return true;
+
+ BinaryOperator *BO = dyn_cast<BinaryOperator>(Builder.GetInsertPoint());
+--- lib/Transforms/Utils/LCSSA.cpp 2014-12-22 14:35:46.000000000 -0800
++++ lib/Transforms/Utils/LCSSA.cpp 2015-11-29 12:35:57.149304063 -0800
+@@ -113,7 +113,8 @@
+ continue;
+
+ PHINode *PN = PHINode::Create(Inst.getType(), PredCache.GetNumPreds(ExitBB),
+- Inst.getName() + ".lcssa", ExitBB->begin());
++ Inst.getName() + ".lcssa",
++ &ExitBB->front());
+
+ // Add inputs from inside the loop for this PHI.
+ for (BasicBlock **PI = PredCache.GetPreds(ExitBB); *PI; ++PI) {
+@@ -161,8 +162,9 @@
+ if (isa<PHINode>(UserBB->begin()) && isExitBlock(UserBB, ExitBlocks)) {
+ // Tell the VHs that the uses changed. This updates SCEV's caches.
+ if (UsesToRewrite[i]->get()->hasValueHandle())
+- ValueHandleBase::ValueIsRAUWd(*UsesToRewrite[i], UserBB->begin());
+- UsesToRewrite[i]->set(UserBB->begin());
++ ValueHandleBase::ValueIsRAUWd(*UsesToRewrite[i],
++ &UserBB->front());
++ UsesToRewrite[i]->set(&UserBB->front());
+ continue;
+ }
+
+--- lib/Transforms/Utils/Local.cpp 2015-02-08 19:35:35.000000000 -0800
++++ lib/Transforms/Utils/Local.cpp 2015-11-29 12:57:42.322148975 -0800
+@@ -419,23 +419,24 @@
+ // or deleted by these simplifications. The idea of simplification is that it
+ // cannot introduce new instructions, and there is no way to replace the
+ // terminator of a block without introducing a new instruction.
+- AssertingVH<Instruction> TerminatorVH(--BB->end());
++ AssertingVH<Instruction> TerminatorVH(&BB->back());
+ #endif
+
+ for (BasicBlock::iterator BI = BB->begin(), E = --BB->end(); BI != E; ) {
+ assert(!BI->isTerminator());
+- Instruction *Inst = BI++;
++ Instruction *Inst = &*BI;
++ ++BI;
+
+- WeakVH BIHandle(BI);
++ WeakVH BIHandle(&*BI);
+ if (recursivelySimplifyInstruction(Inst, TD, TLI)) {
+ MadeChange = true;
+- if (BIHandle != BI)
++ if (BIHandle != &*BI)
+ BI = BB->begin();
+ continue;
+ }
+
+ MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI);
+- if (BIHandle != BI)
++ if (BIHandle != &*BI)
+ BI = BB->begin();
+ }
+ return MadeChange;
+@@ -804,7 +805,8 @@
+
+ // Copy over any phi, debug or lifetime instruction.
+ BB->getTerminator()->eraseFromParent();
+- Succ->getInstList().splice(Succ->getFirstNonPHI(), BB->getInstList());
++ Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(),
++ BB->getInstList());
+ } else {
+ while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
+ // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
+@@ -1054,8 +1056,8 @@
+ DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
+ SmallVector<DbgDeclareInst *, 4> Dbgs;
+ for (auto &FI : F)
+- for (BasicBlock::iterator BI : FI)
+- if (auto DDI = dyn_cast<DbgDeclareInst>(BI))
++ for (Instruction &BI : FI)
++ if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
+ Dbgs.push_back(DDI);
+
+ if (Dbgs.empty())
+@@ -1154,7 +1156,7 @@
+ new UnreachableInst(I->getContext(), I);
+
+ // All instructions after this are dead.
+- BasicBlock::iterator BBI = I, BBE = BB->end();
++ BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
+ while (BBI != BBE) {
+ if (!BBI->use_empty())
+ BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
+@@ -1208,7 +1210,7 @@
+
+ if (MakeUnreachable) {
+ // Don't insert a call to llvm.trap right before the unreachable.
+- changeToUnreachable(BBI, false);
++ changeToUnreachable(&*BBI, false);
+ Changed = true;
+ break;
+ }
+@@ -1222,7 +1224,7 @@
+ ++BBI;
+ if (!isa<UnreachableInst>(BBI)) {
+ // Don't insert a call to llvm.trap right before the unreachable.
+- changeToUnreachable(BBI, false);
++ changeToUnreachable(&*BBI, false);
+ Changed = true;
+ }
+ break;
+@@ -1279,7 +1281,7 @@
+ /// otherwise.
+ bool llvm::removeUnreachableBlocks(Function &F) {
+ SmallPtrSet<BasicBlock*, 128> Reachable;
+- bool Changed = markAliveBlocks(F.begin(), Reachable);
++ bool Changed = markAliveBlocks(&F.front(), Reachable);
+
+ // If there are unreachable blocks in the CFG...
+ if (Reachable.size() == F.size())
+@@ -1291,17 +1293,18 @@
+ // Loop over all of the basic blocks that are not reachable, dropping all of
+ // their internal references...
+ for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) {
+- if (Reachable.count(BB))
++ if (Reachable.count(&*BB))
+ continue;
+
+- for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
++ for (succ_iterator SI = succ_begin(&*BB), SE = succ_end(&*BB);
++ SI != SE; ++SI)
+ if (Reachable.count(*SI))
+- (*SI)->removePredecessor(BB);
++ (*SI)->removePredecessor(&*BB);
+ BB->dropAllReferences();
+ }
+
+ for (Function::iterator I = ++F.begin(); I != F.end();)
+- if (!Reachable.count(I))
++ if (!Reachable.count(&*I))
+ I = F.getBasicBlockList().erase(I);
+ else
+ ++I;
+--- lib/Transforms/Utils/LoopSimplify.cpp 2015-01-04 04:03:27.000000000 -0800
++++ lib/Transforms/Utils/LoopSimplify.cpp 2015-11-29 13:04:06.563171833 -0800
+@@ -76,7 +76,7 @@
+ SmallVectorImpl<BasicBlock *> &SplitPreds,
+ Loop *L) {
+ // Check to see if NewBB is already well placed.
+- Function::iterator BBI = NewBB; --BBI;
++ Function::iterator BBI = --NewBB->getIterator();
+ for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
+ if (&*BBI == SplitPreds[i])
+ return;
+@@ -90,9 +90,8 @@
+ // block that neighbors a BB actually in the loop.
+ BasicBlock *FoundBB = nullptr;
+ for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
+- Function::iterator BBI = SplitPreds[i];
+- if (++BBI != NewBB->getParent()->end() &&
+- L->contains(BBI)) {
++ Function::iterator BBI = SplitPreds[i]->getIterator();
++ if (++BBI != NewBB->getParent()->end() && L->contains(&*BBI)) {
+ FoundBB = SplitPreds[i];
+ break;
+ }
+@@ -392,7 +391,7 @@
+ << BEBlock->getName() << "\n");
+
+ // Move the new backedge block to right after the last backedge block.
+- Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
++ Function::iterator InsertPos = ++BackedgeBlocks.back()->getIterator();
+ F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
+
+ // Now that the block has been inserted into the function, create PHI nodes in
+@@ -651,7 +650,7 @@
+ bool AllInvariant = true;
+ bool AnyInvariant = false;
+ for (BasicBlock::iterator I = ExitingBlock->begin(); &*I != BI; ) {
+- Instruction *Inst = I++;
++ Instruction *Inst = &*I++;
+ // Skip debug info intrinsics.
+ if (isa<DbgInfoIntrinsic>(Inst))
+ continue;
+--- lib/Transforms/Utils/LoopUnrollRuntime.cpp 2015-02-18 14:51:15.000000000 -0800
++++ lib/Transforms/Utils/LoopUnrollRuntime.cpp 2015-11-29 13:08:21.195493550 -0800
+@@ -207,9 +207,9 @@
+ // Change the incoming values to the ones defined in the preheader or
+ // cloned loop.
+ for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
+- PHINode *NewPHI = cast<PHINode>(VMap[I]);
++ PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
+ if (UnrollProlog) {
+- VMap[I] = NewPHI->getIncomingValueForBlock(Preheader);
++ VMap[&*I] = NewPHI->getIncomingValueForBlock(Preheader);
+ cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
+ } else {
+ unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
+@@ -390,8 +390,8 @@
+ VMap, LI);
+
+ // Insert the cloned blocks into function just before the original loop
+- F->getBasicBlockList().splice(PEnd, F->getBasicBlockList(), NewBlocks[0],
+- F->end());
++ F->getBasicBlockList().splice(PEnd->getIterator(), F->getBasicBlockList(),
++ NewBlocks[0]->getIterator(), F->end());
+
+ // Rewrite the cloned instruction operands to use the values
+ // created when the clone is created.
+@@ -399,7 +399,7 @@
+ for (BasicBlock::iterator I = NewBlocks[i]->begin(),
+ E = NewBlocks[i]->end();
+ I != E; ++I) {
+- RemapInstruction(I, VMap,
++ RemapInstruction(&*I, VMap,
+ RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
+ }
+ }
+--- lib/Transforms/Utils/LoopUnroll.cpp 2015-01-04 04:03:27.000000000 -0800
++++ lib/Transforms/Utils/LoopUnroll.cpp 2015-11-29 13:06:17.558243110 -0800
+@@ -383,7 +383,7 @@
+ for (unsigned i = 0; i < NewBlocks.size(); ++i)
+ for (BasicBlock::iterator I = NewBlocks[i]->begin(),
+ E = NewBlocks[i]->end(); I != E; ++I)
+- ::RemapInstruction(I, LastValueMap);
++ ::RemapInstruction(&*I, LastValueMap);
+ }
+
+ // Loop over the PHI nodes in theinal block, setting incoming values.
+@@ -504,7 +504,7 @@
+ for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
+ BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
+ for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
+- Instruction *Inst = I++;
++ Instruction *Inst = &*I++;
+
+ if (isInstructionTriviallyDead(Inst))
+ (*BB)->getInstList().erase(Inst);
+--- lib/Transforms/Utils/LowerExpectIntrinsic.cpp 2014-04-21 19:55:47.000000000 -0700
++++ lib/Transforms/Utils/LowerExpectIntrinsic.cpp 2015-11-29 13:09:35.298686663 -0800
+@@ -148,7 +148,7 @@
+
+ bool LowerExpectIntrinsic::runOnFunction(Function &F) {
+ for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
+- BasicBlock *BB = I++;
++ BasicBlock *BB = &*I++;
+
+ // Create "block_weights" metadata.
+ if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
+--- lib/Transforms/Utils/LowerInvoke.cpp 2014-04-21 19:55:47.000000000 -0700
++++ lib/Transforms/Utils/LowerInvoke.cpp 2015-11-29 13:18:52.019842685 -0800
+@@ -69,7 +69,7 @@
+ BranchInst::Create(II->getNormalDest(), II);
+
+ // Remove any PHI node entries from the exception destination.
+- II->getUnwindDest()->removePredecessor(BB);
++ II->getUnwindDest()->removePredecessor(&*BB);
+
+ // Remove the invoke instruction now.
+ BB->getInstList().erase(II);
+--- lib/Transforms/Utils/LowerSwitch.cpp 2015-01-28 09:35:18.000000000 -0800
++++ lib/Transforms/Utils/LowerSwitch.cpp 2015-11-29 13:39:46.489837410 -0800
+@@ -101,7 +101,8 @@
+ bool Changed = false;
+
+ for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
+- BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
++ BasicBlock *Cur = &*I; // Advance over block so we don't traverse new blocks
++ ++I;
+
+ if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
+ Changed = true;
+@@ -142,7 +143,8 @@
+ // number of phi values equal to the number of branches to SuccBB.
+ static void fixPhis(BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB,
+ unsigned NumMergedCases) {
+- for (BasicBlock::iterator I = SuccBB->begin(), IE = SuccBB->getFirstNonPHI();
++ for (BasicBlock::iterator I = SuccBB->begin(),
++ IE = SuccBB->getFirstNonPHI()->getIterator();
+ I != IE; ++I) {
+ PHINode *PN = cast<PHINode>(I);
+
+@@ -256,8 +258,7 @@
+ UpperBound, Val, NewNode, OrigBlock,
+ Default);
+
+- Function::iterator FI = OrigBlock;
+- F->getBasicBlockList().insert(++FI, NewNode);
++ F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewNode);
+ NewNode->getInstList().push_back(Comp);
+
+ BranchInst::Create(LBranch, RBranch, Comp, NewNode);
+@@ -276,8 +277,7 @@
+ {
+ Function* F = OrigBlock->getParent();
+ BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
+- Function::iterator FI = OrigBlock;
+- F->getBasicBlockList().insert(++FI, NewLeaf);
++ F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewLeaf);
+
+ // Emit comparison
+ ICmpInst* Comp = nullptr;
+@@ -395,8 +395,7 @@
+ BasicBlock *NewDefault = nullptr;
+ if (!DefaultIsUnreachable) {
+ NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
+- F->getBasicBlockList().insert(Default, NewDefault);
+-
++ F->getBasicBlockList().insert(Default->getIterator(), NewDefault);
+ BranchInst::Create(Default, NewDefault);
+ }
+ // If there is an entry in any PHI nodes for the default edge, make sure
+--- lib/Transforms/Utils/PromoteMemoryToRegister.cpp 2015-01-04 04:03:27.000000000 -0800
++++ lib/Transforms/Utils/PromoteMemoryToRegister.cpp 2015-11-29 13:44:30.613019495 -0800
+@@ -214,10 +214,11 @@
+ // avoid gratuitus rescans.
+ const BasicBlock *BB = I->getParent();
+ unsigned InstNo = 0;
+- for (BasicBlock::const_iterator BBI = BB->begin(), E = BB->end(); BBI != E;
+- ++BBI)
+- if (isInterestingInstruction(BBI))
+- InstNumbers[BBI] = InstNo++;
++
++ for (const Instruction &BBI : *BB)
++ if (isInterestingInstruction(&BBI))
++ InstNumbers[&BBI] = InstNo++;
++
+ It = InstNumbers.find(I);
+
+ assert(It != InstNumbers.end() && "Didn't insert instruction?");
+@@ -602,7 +603,7 @@
+ if (BBNumbers.empty()) {
+ unsigned ID = 0;
+ for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
+- BBNumbers[I] = ID++;
++ BBNumbers[&*I] = ID++;
+ }
+
+ // If we have an AST to keep updated, remember some pointer value that is
+@@ -641,7 +642,7 @@
+ // and inserting the phi nodes we marked as necessary
+ //
+ std::vector<RenamePassData> RenamePassWorkList;
+- RenamePassWorkList.push_back(RenamePassData(F.begin(), nullptr, Values));
++ RenamePassWorkList.push_back(RenamePassData(&F.front(), nullptr, Values));
+ do {
+ RenamePassData RPD;
+ RPD.swap(RenamePassWorkList.back());
+@@ -946,7 +947,7 @@
+ // BasicBlock.
+ PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
+ Allocas[AllocaNo]->getName() + "." + Twine(Version++),
+- BB->begin());
++ &BB->front());
+ ++NumPHIInsert;
+ PhiToAllocaMap[PN] = AllocaNo;
+
+@@ -1011,7 +1012,8 @@
+ return;
+
+ for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II);) {
+- Instruction *I = II++; // get the instruction, increment iterator
++ Instruction *I = &*II; // get the instruction, increment iterator
++ ++II;
+
+ if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
+ AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
+--- lib/Transforms/Utils/SimplifyCFG.cpp 2015-01-12 20:17:47.000000000 -0800
++++ lib/Transforms/Utils/SimplifyCFG.cpp 2015-11-29 15:07:34.912976680 -0800
+@@ -1091,15 +1091,15 @@
+ BasicBlock::iterator BB1_Itr = BB1->begin();
+ BasicBlock::iterator BB2_Itr = BB2->begin();
+
+- Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
++ Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
+ // Skip debug info if it is not identical.
+ DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
+ DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
+ if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
+ while (isa<DbgInfoIntrinsic>(I1))
+- I1 = BB1_Itr++;
++ I1 = &*BB1_Itr++;
+ while (isa<DbgInfoIntrinsic>(I2))
+- I2 = BB2_Itr++;
++ I2 = &*BB2_Itr++;
+ }
+ if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
+ (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
+@@ -1117,7 +1117,7 @@
+ // For a normal instruction, we just move one to right before the branch,
+ // then replace all uses of the other with the first. Finally, we remove
+ // the now redundant second instruction.
+- BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
++ BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(), I1);
+ if (!I2->use_empty())
+ I2->replaceAllUsesWith(I1);
+ I1->intersectOptionalDataWith(I2);
+@@ -1132,16 +1132,16 @@
+ I2->eraseFromParent();
+ Changed = true;
+
+- I1 = BB1_Itr++;
+- I2 = BB2_Itr++;
++ I1 = &*BB1_Itr++;
++ I2 = &*BB2_Itr++;
+ // Skip debug info if it is not identical.
+ DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
+ DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
+ if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
+ while (isa<DbgInfoIntrinsic>(I1))
+- I1 = BB1_Itr++;
++ I1 = &*BB1_Itr++;
+ while (isa<DbgInfoIntrinsic>(I2))
+- I2 = BB2_Itr++;
++ I2 = &*BB2_Itr++;
+ }
+ } while (I1->isIdenticalToWhenDefined(I2));
+
+@@ -1176,7 +1176,7 @@
+
+ // Okay, it is safe to hoist the terminator.
+ Instruction *NT = I1->clone();
+- BIParent->getInstList().insert(BI, NT);
++ BIParent->getInstList().insert(BI->getIterator(), NT);
+ if (!NT->getType()->isVoidTy()) {
+ I1->replaceAllUsesWith(NT);
+ I2->replaceAllUsesWith(NT);
+@@ -1353,7 +1353,7 @@
+ if (!NewPN) {
+ NewPN =
+ PHINode::Create(DifferentOp1->getType(), 2,
+- DifferentOp1->getName() + ".sink", BBEnd->begin());
++ DifferentOp1->getName() + ".sink", &BBEnd->front());
+ NewPN->addIncoming(DifferentOp1, BB1);
+ NewPN->addIncoming(DifferentOp2, BB2);
+ DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
+@@ -1368,7 +1368,8 @@
+ // instruction in the basic block down.
+ bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
+ // Sink the instruction.
+- BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
++ BBEnd->getInstList().splice(FirstNonPhiInBBEnd->getIterator(),
++ BB1->getInstList(), I1);
+ if (!OldPN->use_empty())
+ OldPN->replaceAllUsesWith(I1);
+ OldPN->eraseFromParent();
+@@ -1520,7 +1521,7 @@
+ for (BasicBlock::iterator BBI = ThenBB->begin(),
+ BBE = std::prev(ThenBB->end());
+ BBI != BBE; ++BBI) {
+- Instruction *I = BBI;
++ Instruction *I = &*BBI;
+ // Skip debug info.
+ if (isa<DbgInfoIntrinsic>(I))
+ continue;
+@@ -1632,8 +1633,8 @@
+ }
+
+ // Hoist the instructions.
+- BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
+- std::prev(ThenBB->end()));
++ BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
++ ThenBB->begin(), std::prev(ThenBB->end()));
+
+ // Insert selects and rewrite the PHI operands.
+ IRBuilder<true, NoFolder> Builder(BI);
+@@ -1776,13 +1777,13 @@
+
+ // Check for trivial simplification.
+ if (Value *V = SimplifyInstruction(N, DL)) {
+- TranslateMap[BBI] = V;
++ TranslateMap[&*BBI] = V;
+ delete N; // Instruction folded away, don't need actual inst
+ } else {
+ // Insert the new instruction into its new home.
+ EdgeBB->getInstList().insert(InsertPt, N);
+ if (!BBI->use_empty())
+- TranslateMap[BBI] = N;
++ TranslateMap[&*BBI] = N;
+ }
+ }
+
+@@ -1875,8 +1876,9 @@
+ IfBlock1 = nullptr;
+ } else {
+ DomBlock = *pred_begin(IfBlock1);
+- for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
+- if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
++ for (BasicBlock::iterator I = IfBlock1->begin();
++ !isa<TerminatorInst>(I); ++I)
++ if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
+ // This is not an aggressive instruction that we can promote.
+ // Because of this, we won't be able to get rid of the control
+ // flow, so the xform is not worth it.
+@@ -1888,8 +1890,9 @@
+ IfBlock2 = nullptr;
+ } else {
+ DomBlock = *pred_begin(IfBlock2);
+- for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
+- if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
++ for (BasicBlock::iterator I = IfBlock2->begin();
++ !isa<TerminatorInst>(I); ++I)
++ if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
+ // This is not an aggressive instruction that we can promote.
+ // Because of this, we won't be able to get rid of the control
+ // flow, so the xform is not worth it.
+@@ -1908,13 +1911,13 @@
+ // Move all 'aggressive' instructions, which are defined in the
+ // conditional parts of the if's up to the dominating block.
+ if (IfBlock1)
+- DomBlock->getInstList().splice(InsertPt,
++ DomBlock->getInstList().splice(InsertPt->getIterator(),
+ IfBlock1->getInstList(), IfBlock1->begin(),
+- IfBlock1->getTerminator());
++ IfBlock1->getTerminator()->getIterator());
+ if (IfBlock2)
+- DomBlock->getInstList().splice(InsertPt,
++ DomBlock->getInstList().splice(InsertPt->getIterator(),
+ IfBlock2->getInstList(), IfBlock2->begin(),
+- IfBlock2->getTerminator());
++ IfBlock2->getTerminator()->getIterator());
+
+ while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
+ // Change the PHI node into a select instruction.
+@@ -2086,7 +2089,8 @@
+ BI->getSuccessor(0) == PBI->getSuccessor(1))) {
+ for (BasicBlock::iterator I = BB->begin(), E = BB->end();
+ I != E; ) {
+- Instruction *Curr = I++;
++ Instruction *Curr = &*I;
++ ++I;
+ if (isa<CmpInst>(Curr)) {
+ Cond = Curr;
+ break;
+@@ -2106,7 +2110,7 @@
+ return false;
+
+ // Make sure the instruction after the condition is the cond branch.
+- BasicBlock::iterator CondIt = Cond; ++CondIt;
++ BasicBlock::iterator CondIt = ++Cond->getIterator();
+
+ // Ignore dbg intrinsics.
+ while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
+@@ -2124,7 +2128,7 @@
+ // Ignore dbg intrinsics.
+ if (isa<DbgInfoIntrinsic>(I))
+ continue;
+- if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(I, DL))
++ if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I, DL))
+ return false;
+ // I has only one use and can be executed unconditionally.
+ Instruction *User = dyn_cast<Instruction>(I->user_back());
+@@ -2221,7 +2225,7 @@
+ Instruction *NewBonusInst = BonusInst->clone();
+ RemapInstruction(NewBonusInst, VMap,
+ RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
+- VMap[BonusInst] = NewBonusInst;
++ VMap[&*BonusInst] = NewBonusInst;
+
+ // If we moved a load, we cannot any longer claim any knowledge about
+ // its potential value. The previous information might have been valid
+@@ -2230,8 +2234,8 @@
+ // semantics we don't understand.
+ NewBonusInst->dropUnknownMetadata(LLVMContext::MD_dbg);
+
+- PredBlock->getInstList().insert(PBI, NewBonusInst);
+- NewBonusInst->takeName(BonusInst);
++ PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
++ NewBonusInst->takeName(&*BonusInst);
+ BonusInst->setName(BonusInst->getName() + ".old");
+ }
+
+@@ -2240,7 +2244,7 @@
+ Instruction *New = Cond->clone();
+ RemapInstruction(New, VMap,
+ RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
+- PredBlock->getInstList().insert(PBI, New);
++ PredBlock->getInstList().insert(PBI->getIterator(), New);
+ New->takeName(Cond);
+ Cond->setName(New->getName() + ".old");
+
+@@ -2392,7 +2396,7 @@
+ PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
+ std::distance(PB, PE),
+ BI->getCondition()->getName() + ".pr",
+- BB->begin());
++ &BB->front());
+ // Okay, we're going to insert the PHI node. Since PBI is not the only
+ // predecessor, compute the PHI'd conditional value for all of the preds.
+ // Any predecessor where the condition is not computable we keep symbolic.
+@@ -2877,7 +2881,9 @@
+ // then we evaluate them with an explicit branch first. Split the block
+ // right before the condbr to handle it.
+ if (ExtraCase) {
+- BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
++ BasicBlock *NewBB =
++ BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
++
+ // Remove the uncond branch added to the old block.
+ TerminatorInst *OldTI = BB->getTerminator();
+ Builder.SetInsertPoint(OldTI);
+@@ -2943,7 +2949,7 @@
+ return false;
+
+ // Check that there are no other instructions except for debug intrinsics.
+- BasicBlock::iterator I = LPInst, E = RI;
++ BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
+ while (++I != E)
+ if (!isa<DbgInfoIntrinsic>(I))
+ return false;
+@@ -3049,8 +3055,8 @@
+
+ // If there are any instructions immediately before the unreachable that can
+ // be removed, do so.
+- while (UI != BB->begin()) {
+- BasicBlock::iterator BBI = UI;
++ while (UI->getIterator() != BB->begin()) {
++ BasicBlock::iterator BBI = UI->getIterator();
+ --BBI;
+ // Do not delete instructions that can have side effects which might cause
+ // the unreachable to not be reachable; specifically, calls and volatile
+@@ -3484,7 +3490,7 @@
+ } else if (isa<DbgInfoIntrinsic>(I)) {
+ // Skip debug intrinsic.
+ continue;
+- } else if (Constant *C = ConstantFold(I, ConstantPool, DL)) {
++ } else if (Constant *C = ConstantFold(&*I, ConstantPool, DL)) {
+ // Instruction is side-effect free and constant.
+
+ // If the instruction has uses outside this block or a phi node slot for
+@@ -3501,7 +3507,7 @@
+ return false;
+ }
+
+- ConstantPool.insert(std::make_pair(I, C));
++ ConstantPool.insert(std::make_pair(&*I, C));
+ } else {
+ break;
+ }
+@@ -4399,7 +4405,7 @@
+ return true;
+
+ // If the Terminator is the only non-phi instruction, simplify the block.
+- BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
++ BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
+ if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
+ TryToSimplifyUncondBranchFromEmptyBlock(BB))
+ return true;
+--- lib/Transforms/Utils/SimplifyInstructions.cpp 2015-01-04 04:03:27.000000000 -0800
++++ lib/Transforms/Utils/SimplifyInstructions.cpp 2015-11-29 15:09:24.682261310 -0800
+@@ -63,8 +63,11 @@
+ for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
+ // Here be subtlety: the iterator must be incremented before the loop
+ // body (not sure why), so a range-for loop won't work here.
+- for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
+- Instruction *I = BI++;
++ for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
++ BI != BE; /* inside loop */) {
++ Instruction *I = &*BI;
++ ++BI;
++
+ // The first time through the loop ToSimplify is empty and we try to
+ // simplify all instructions. On later iterations ToSimplify is not
+ // empty and we only bother simplifying instructions that are in it.
+--- lib/Transforms/Utils/SimplifyLibCalls.cpp 2015-01-28 11:15:34.000000000 -0800
++++ lib/Transforms/Utils/SimplifyLibCalls.cpp 2015-11-29 15:11:56.561911410 -0800
+@@ -1338,8 +1338,7 @@
+ if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
+ // If the argument is an instruction, it must dominate all uses so put our
+ // sincos call there.
+- BasicBlock::iterator Loc = ArgInst;
+- B.SetInsertPoint(ArgInst->getParent(), ++Loc);
++ B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
+ } else {
+ // Otherwise (e.g. for a constant) the beginning of the function is as
+ // good a place as any.
+--- lib/Transforms/Utils/UnifyFunctionExitNodes.cpp 2015-01-28 09:35:18.000000000 -0800
++++ lib/Transforms/Utils/UnifyFunctionExitNodes.cpp 2015-11-29 15:14:01.147224983 -0800
+@@ -50,11 +50,12 @@
+ //
+ std::vector<BasicBlock*> ReturningBlocks;
+ std::vector<BasicBlock*> UnreachableBlocks;
+- for(Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
+- if (isa<ReturnInst>(I->getTerminator()))
+- ReturningBlocks.push_back(I);
+- else if (isa<UnreachableInst>(I->getTerminator()))
+- UnreachableBlocks.push_back(I);
++
++ for (BasicBlock &I : F)
++ if (isa<ReturnInst>(I.getTerminator()))
++ ReturningBlocks.push_back(&I);
++ else if (isa<UnreachableInst>(I.getTerminator()))
++ UnreachableBlocks.push_back(&I);
+
+ // Then unreachable blocks.
+ if (UnreachableBlocks.empty()) {
+--- lib/Transforms/Vectorize/BBVectorize.cpp 2014-12-19 09:21:38.000000000 -0800
++++ lib/Transforms/Vectorize/BBVectorize.cpp 2015-12-06 09:35:21.191615227 -0800
+@@ -1243,12 +1243,13 @@
+ if (I == Start) IAfterStart = true;
+
+ bool IsSimpleLoadStore;
+- if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
++ if (!isInstVectorizable(&*I, IsSimpleLoadStore)) continue;
+
+ // Look for an instruction with which to pair instruction *I...
+ DenseSet<Value *> Users;
+ AliasSetTracker WriteSet(*AA);
+- if (I->mayWriteToMemory()) WriteSet.add(I);
++ if (I->mayWriteToMemory())
++ WriteSet.add(&*I);
+
+ bool JAfterStart = IAfterStart;
+ BasicBlock::iterator J = std::next(I);
+@@ -1256,7 +1257,7 @@
+ if (J == Start) JAfterStart = true;
+
+ // Determine if J uses I, if so, exit the loop.
+- bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !Config.FastDep);
++ bool UsesI = trackUsesOfI(Users, WriteSet, &*I, &*J, !Config.FastDep);
+ if (Config.FastDep) {
+ // Note: For this heuristic to be effective, independent operations
+ // must tend to be intermixed. This is likely to be true from some
+@@ -1273,25 +1274,26 @@
+ // J does not use I, and comes before the first use of I, so it can be
+ // merged with I if the instructions are compatible.
+ int CostSavings, FixedOrder;
+- if (!areInstsCompatible(I, J, IsSimpleLoadStore, NonPow2Len,
+- CostSavings, FixedOrder)) continue;
++ if (!areInstsCompatible(&*I, &*J, IsSimpleLoadStore, NonPow2Len,
++ CostSavings, FixedOrder))
++ continue;
+
+ // J is a candidate for merging with I.
+ if (!PairableInsts.size() ||
+- PairableInsts[PairableInsts.size()-1] != I) {
+- PairableInsts.push_back(I);
++ PairableInsts[PairableInsts.size()-1] != &*I) {
++ PairableInsts.push_back(&*I);
+ }
+
+- CandidatePairs[I].push_back(J);
++ CandidatePairs[&*I].push_back(&*J);
+ ++TotalPairs;
+ if (TTI)
+- CandidatePairCostSavings.insert(ValuePairWithCost(ValuePair(I, J),
+- CostSavings));
++ CandidatePairCostSavings.insert(
++ ValuePairWithCost(ValuePair(&*I, &*J), CostSavings));
+
+ if (FixedOrder == 1)
+- FixedOrderPairs.insert(ValuePair(I, J));
++ FixedOrderPairs.insert(ValuePair(&*I, &*J));
+ else if (FixedOrder == -1)
+- FixedOrderPairs.insert(ValuePair(J, I));
++ FixedOrderPairs.insert(ValuePair(&*J, &*I));
+
+ // The next call to this function must start after the last instruction
+ // selected during this invocation.
+@@ -1472,14 +1474,15 @@
+ BasicBlock::iterator E = BB.end(), EL =
+ BasicBlock::iterator(cast<Instruction>(PairableInsts.back()));
+ for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
+- if (IsInPair.find(I) == IsInPair.end()) continue;
++ if (IsInPair.find(&*I) == IsInPair.end())
++ continue;
+
+ DenseSet<Value *> Users;
+ AliasSetTracker WriteSet(*AA);
+- if (I->mayWriteToMemory()) WriteSet.add(I);
++ if (I->mayWriteToMemory()) WriteSet.add(&*I);
+
+ for (BasicBlock::iterator J = std::next(I); J != E; ++J) {
+- (void) trackUsesOfI(Users, WriteSet, I, J);
++ (void) trackUsesOfI(Users, WriteSet, &*I, &*J);
+
+ if (J == EL)
+ break;
+@@ -1488,7 +1491,7 @@
+ for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
+ U != E; ++U) {
+ if (IsInPair.find(*U) == IsInPair.end()) continue;
+- PairableInstUsers.insert(ValuePair(I, *U));
++ PairableInstUsers.insert(ValuePair(&*I, *U));
+ }
+
+ if (I == EL)
+@@ -2873,7 +2876,7 @@
+ if (I->mayWriteToMemory()) WriteSet.add(I);
+
+ for (; cast<Instruction>(L) != J; ++L)
+- (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs);
++ (void) trackUsesOfI(Users, WriteSet, I, &*L, true, &LoadMoveSetPairs);
+
+ assert(cast<Instruction>(L) == J &&
+ "Tracking has not proceeded far enough to check for dependencies");
+@@ -2895,9 +2898,10 @@
+ if (I->mayWriteToMemory()) WriteSet.add(I);
+
+ for (; cast<Instruction>(L) != J;) {
+- if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs)) {
++ if (trackUsesOfI(Users, WriteSet, I, &*L, true, &LoadMoveSetPairs)) {
+ // Move this instruction
+- Instruction *InstToMove = L; ++L;
++ Instruction *InstToMove = &*L;
++ ++L;
+
+ DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
+ " to after " << *InsertionPt << "\n");
+@@ -2929,10 +2933,10 @@
+ // farther down the use chain by another instruction pairing. Also, J
+ // could be before I if this is an inverted input.
+ for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
+- if (trackUsesOfI(Users, WriteSet, I, L)) {
++ if (trackUsesOfI(Users, WriteSet, I, &*L)) {
+ if (L->mayReadFromMemory()) {
+- LoadMoveSet[L].push_back(I);
+- LoadMoveSetPairs.insert(ValuePair(L, I));
++ LoadMoveSet[&*L].push_back(I);
++ LoadMoveSetPairs.insert(ValuePair(&*L, I));
+ }
+ }
+ }
+@@ -2995,7 +2999,7 @@
+ DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
+
+ for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
+- DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
++ DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(&*PI);
+ if (P == ChosenPairs.end()) {
+ ++PI;
+ continue;
+--- lib/Transforms/Vectorize/LoopVectorize.cpp 2015-02-17 13:53:25.000000000 -0800
++++ lib/Transforms/Vectorize/LoopVectorize.cpp 2015-12-06 11:41:36.696287648 -0800
+@@ -462,6 +462,10 @@
+ Value *ExtendedIdx;
+ /// Maps scalars to widened vectors.
+ ValueMap WidenMap;
++ /// Store instructions that should be predicated, as a pair
++ /// <StoreInst, Predicate>
++ SmallVector<std::pair<StoreInst*,Value*>, 4> PredicatedStores;
++
+ EdgeMaskCache MaskCache;
+
+ LoopVectorizationLegality *Legal;
+@@ -1965,36 +1969,31 @@
+ // Create a new entry in the WidenMap and initialize it to Undef or Null.
+ VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
+
+- Instruction *InsertPt = Builder.GetInsertPoint();
+- BasicBlock *IfBlock = Builder.GetInsertBlock();
+- BasicBlock *CondBlock = nullptr;
++ // Instruction *InsertPt = Builder.GetInsertPoint();
++ // BasicBlock *IfBlock = Builder.GetInsertBlock();
++ // BasicBlock *CondBlock = nullptr;
+
+ VectorParts Cond;
+- Loop *VectorLp = nullptr;
++ // Loop *VectorLp = nullptr;
+ if (IfPredicateStore) {
+ assert(Instr->getParent()->getSinglePredecessor() &&
+ "Only support single predecessor blocks");
+ Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
+ Instr->getParent());
+- VectorLp = LI->getLoopFor(IfBlock);
+- assert(VectorLp && "Must have a loop for this block");
++ // VectorLp = LI->getLoopFor(IfBlock);
++ // assert(VectorLp && "Must have a loop for this block");
+ }
+
+ // For each vector unroll 'part':
+ for (unsigned Part = 0; Part < UF; ++Part) {
+ // For each scalar that we create:
+ for (unsigned Width = 0; Width < VF; ++Width) {
+-
+ // Start if-block.
+ Value *Cmp = nullptr;
+ if (IfPredicateStore) {
+ Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
+- Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
+- CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
+- LoopVectorBody.push_back(CondBlock);
+- VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
+- // Update Builder with newly created basic block.
+- Builder.SetInsertPoint(InsertPt);
++ Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp,
++ ConstantInt::get(Cmp->getType(), 1));
+ }
+
+ Instruction *Cloned = Instr->clone();
+@@ -2019,6 +2018,7 @@
+ Builder.getInt32(Width));
+ // End if-block.
+ if (IfPredicateStore) {
++#if 0
+ BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
+ LoopVectorBody.push_back(NewIfBlock);
+ VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
+@@ -2027,6 +2027,9 @@
+ BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
+ OldBr->eraseFromParent();
+ IfBlock = NewIfBlock;
++#endif
++ PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned),
++ Cmp));
+ }
+ }
+ }
+@@ -2283,13 +2286,17 @@
+
+ // Split the single block loop into the two loop structure described above.
+ BasicBlock *VectorPH =
+- BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
++ BypassBlock->splitBasicBlock(BypassBlock->getTerminator()->getIterator(),
++ "vector.ph");
+ BasicBlock *VecBody =
+- VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
++ VectorPH->splitBasicBlock(VectorPH->getTerminator()->getIterator(),
++ "vector.body");
+ BasicBlock *MiddleBlock =
+- VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
++ VecBody->splitBasicBlock(VecBody->getTerminator()->getIterator(),
++ "middle.block");
+ BasicBlock *ScalarPH =
+- MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
++ MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator()->getIterator(),
++ "scalar.ph");
+
+ // Create and register the new vector loop.
+ Loop* Lp = new Loop();
+@@ -2378,7 +2385,8 @@
+ if (StrideCheck) {
+ // Create a new block containing the stride check.
+ BasicBlock *CheckBlock =
+- LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
++ LastBypassBlock->splitBasicBlock(FirstCheckInst->getIterator(),
++ "vector.stridecheck");
+ if (ParentLoop)
+ ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
+ LoopBypassBlocks.push_back(CheckBlock);
+@@ -2402,7 +2410,8 @@
+ if (MemRuntimeCheck) {
+ // Create a new block containing the memory check.
+ BasicBlock *CheckBlock =
+- LastBypassBlock->splitBasicBlock(MemRuntimeCheck, "vector.memcheck");
++ LastBypassBlock->splitBasicBlock(MemRuntimeCheck->getIterator(),
++ "vector.memcheck");
+ if (ParentLoop)
+ ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
+ LoopBypassBlocks.push_back(CheckBlock);
+@@ -2590,7 +2599,7 @@
+ VecBody->getTerminator()->eraseFromParent();
+
+ // Get ready to start creating new instructions into the vectorized body.
+- Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
++ Builder.SetInsertPoint(&*VecBody->getFirstInsertionPt());
+
+ // Save the state.
+ LoopVectorPreHeader = VectorPH;
+@@ -2739,7 +2748,8 @@
+ for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
+ BasicBlock *BB = BBs[i];
+ for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
+- Instruction *In = I++;
++ Instruction *In = &*I;
++ ++I;
+
+ if (!CSEDenseMapInfo::canHandle(In))
+ continue;
+@@ -2890,7 +2900,7 @@
+ // the PHIs and the values we are going to write.
+ // This allows us to write both PHINodes and the extractelement
+ // instructions.
+- Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
++ Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
+
+ VectorParts RdxParts;
+ setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
+@@ -3000,6 +3010,9 @@
+
+ fixLCSSAPHIs();
+
++ // Make sure DomTree is updated.
++ updateAnalysis();
++
+ // Remove redundant induction instructions.
+ cse(LoopVectorBody);
+ }
+@@ -3084,8 +3097,9 @@
+ // This is phase one of vectorizing PHIs.
+ Type *VecTy = (VF == 1) ? PN->getType() :
+ VectorType::get(PN->getType(), VF);
+- Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
+- LoopVectorBody.back()-> getFirstInsertionPt());
++ Entry[part] =
++ PHINode::Create(VecTy, 2, "vec.phi",
++ &*LoopVectorBody.back()->getFirstInsertionPt());
+ }
+ PV->push_back(P);
+ return;
+@@ -3240,7 +3254,7 @@
+ void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
+ // For each instruction in the old loop.
+ for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
+- VectorParts &Entry = WidenMap.get(it);
++ VectorParts &Entry = WidenMap.get(&*it);
+ switch (it->getOpcode()) {
+ case Instruction::Br:
+ // Nothing to do for PHIs and BR, since we already took care of the
+@@ -3248,7 +3262,7 @@
+ continue;
+ case Instruction::PHI:{
+ // Vectorize PHINodes.
+- widenPHIInstruction(it, Entry, UF, VF, PV);
++ widenPHIInstruction(&*it, Entry, UF, VF, PV);
+ continue;
+ }// End of PHI.
+
+@@ -3286,7 +3300,7 @@
+ Entry[Part] = V;
+ }
+
+- propagateMetadata(Entry, it);
++ propagateMetadata(Entry, &*it);
+ break;
+ }
+ case Instruction::Select: {
+@@ -3295,7 +3309,7 @@
+ // instruction with a scalar condition. Otherwise, use vector-select.
+ bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
+ OrigLoop);
+- setDebugLocFromInst(Builder, it);
++ setDebugLocFromInst(Builder, &*it);
+
+ // The condition can be loop invariant but still defined inside the
+ // loop. This means that we can't just use theinal 'cond' value.
+@@ -3315,7 +3329,7 @@
+ Op1[Part]);
+ }
+
+- propagateMetadata(Entry, it);
++ propagateMetadata(Entry, &*it);
+ break;
+ }
+
+@@ -3324,7 +3338,7 @@
+ // Widen compares. Generate vector compares.
+ bool FCmp = (it->getOpcode() == Instruction::FCmp);
+ CmpInst *Cmp = dyn_cast<CmpInst>(it);
+- setDebugLocFromInst(Builder, it);
++ setDebugLocFromInst(Builder, &*it);
+ VectorParts &A = getVectorValue(it->getOperand(0));
+ VectorParts &B = getVectorValue(it->getOperand(1));
+ for (unsigned Part = 0; Part < UF; ++Part) {
+@@ -3336,13 +3350,13 @@
+ Entry[Part] = C;
+ }
+
+- propagateMetadata(Entry, it);
++ propagateMetadata(Entry, &*it);
+ break;
+ }
+
+ case Instruction::Store:
+ case Instruction::Load:
+- vectorizeMemoryInstruction(it);
++ vectorizeMemoryInstruction(&*it);
+ break;
+ case Instruction::ZExt:
+ case Instruction::SExt:
+@@ -3357,7 +3371,7 @@
+ case Instruction::FPTrunc:
+ case Instruction::BitCast: {
+ CastInst *CI = dyn_cast<CastInst>(it);
+- setDebugLocFromInst(Builder, it);
++ setDebugLocFromInst(Builder, &*it);
+ /// Optimize the special case where the source is the induction
+ /// variable. Notice that we can only optimize the 'trunc' case
+ /// because: a. FP conversions lose precision, b. sext/zext may wrap,
+@@ -3369,7 +3383,7 @@
+ Value *Broadcasted = getBroadcastInstrs(ScalarCast);
+ for (unsigned Part = 0; Part < UF; ++Part)
+ Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
+- propagateMetadata(Entry, it);
++ propagateMetadata(Entry, &*it);
+ break;
+ }
+ /// Vectorize casts.
+@@ -3379,7 +3393,7 @@
+ VectorParts &A = getVectorValue(it->getOperand(0));
+ for (unsigned Part = 0; Part < UF; ++Part)
+ Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
+- propagateMetadata(Entry, it);
++ propagateMetadata(Entry, &*it);
+ break;
+ }
+
+@@ -3387,7 +3401,7 @@
+ // Ignore dbg intrinsics.
+ if (isa<DbgInfoIntrinsic>(it))
+ break;
+- setDebugLocFromInst(Builder, it);
++ setDebugLocFromInst(Builder, &*it);
+
+ Module *M = BB->getParent()->getParent();
+ CallInst *CI = cast<CallInst>(it);
+@@ -3397,7 +3411,7 @@
+ case Intrinsic::assume:
+ case Intrinsic::lifetime_end:
+ case Intrinsic::lifetime_start:
+- scalarizeInstruction(it);
++ scalarizeInstruction(&*it);
+ break;
+ default:
+ bool HasScalarOpd = hasVectorInstrinsicScalarOpd(ID, 1);
+@@ -3419,7 +3433,7 @@
+ Entry[Part] = Builder.CreateCall(F, Args);
+ }
+
+- propagateMetadata(Entry, it);
++ propagateMetadata(Entry, &*it);
+ break;
+ }
+ break;
+@@ -3427,7 +3441,7 @@
+
+ default:
+ // All other instructions are unsupported. Scalarize them.
+- scalarizeInstruction(it);
++ scalarizeInstruction(&*it);
+ break;
+ }// end of switch.
+ }// end of for_each instr.
+@@ -3686,7 +3700,7 @@
+ if (!PhiTy->isIntegerTy() &&
+ !PhiTy->isFloatingPointTy() &&
+ !PhiTy->isPointerTy()) {
+- emitAnalysis(Report(it)
++ emitAnalysis(Report(&*it)
+ << "loop control flow is not understood by vectorizer");
+ DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
+ return false;
+@@ -3698,16 +3712,17 @@
+ if (*bb != Header) {
+ // Check that this instruction has no outside users or is an
+ // identified reduction value with an outside user.
+- if (!hasOutsideLoopUser(TheLoop, it, AllowedExit))
++ if (!hasOutsideLoopUser(TheLoop, &*it, AllowedExit))
+ continue;
+- emitAnalysis(Report(it) << "value could not be identified as "
+- "an induction or reduction variable");
++ emitAnalysis(Report(&*it)
++ << "value could not be identified as "
++ "an induction or reduction variable");
+ return false;
+ }
+
+ // We only allow if-converted PHIs with exactly two incoming values.
+ if (Phi->getNumIncomingValues() != 2) {
+- emitAnalysis(Report(it)
++ emitAnalysis(Report(&*it)
+ << "control flow not understood by vectorizer");
+ DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
+ return false;
+@@ -3739,9 +3754,10 @@
+
+ // Until we explicitly handle the case of an induction variable with
+ // an outside loop user we have to give up vectorizing this loop.
+- if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
+- emitAnalysis(Report(it) << "use of induction value outside of the "
+- "loop is not handled by vectorizer");
++ if (hasOutsideLoopUser(TheLoop, &*it, AllowedExit)) {
++ emitAnalysis(Report(&*it) <<
++ "use of induction value outside of the "
++ "loop is not handled by vectorizer");
+ return false;
+ }
+
+@@ -3786,8 +3802,8 @@
+ continue;
+ }
+
+- emitAnalysis(Report(it) << "value that could not be identified as "
+- "reduction is used outside the loop");
++ emitAnalysis(Report(&*it) << "value that could not be identified as "
++ "reduction is used outside the loop");
+ DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
+ return false;
+ }// end of PHI handling
+@@ -3796,7 +3812,7 @@
+ // calls and we do handle certain intrinsic and libm functions.
+ CallInst *CI = dyn_cast<CallInst>(it);
+ if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
+- emitAnalysis(Report(it) << "call instruction cannot be vectorized");
++ emitAnalysis(Report(&*it) << "call instruction cannot be vectorized");
+ DEBUG(dbgs() << "LV: Found a call site.\n");
+ return false;
+ }
+@@ -3806,7 +3822,7 @@
+ if (CI &&
+ hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
+ if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
+- emitAnalysis(Report(it)
++ emitAnalysis(Report(&*it)
+ << "intrinsic instruction cannot be vectorized");
+ DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
+ return false;
+@@ -3817,7 +3833,7 @@
+ // Also, we can't vectorize extractelement instructions.
+ if ((!VectorType::isValidElementType(it->getType()) &&
+ !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
+- emitAnalysis(Report(it)
++ emitAnalysis(Report(&*it)
+ << "instruction return type cannot be vectorized");
+ DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
+ return false;
+@@ -3840,8 +3856,8 @@
+
+ // Reduction instructions are allowed to have exit users.
+ // All other instructions must not have external users.
+- if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
+- emitAnalysis(Report(it) << "value cannot be used outside the loop");
++ if (hasOutsideLoopUser(TheLoop, &*it, AllowedExit)) {
++ emitAnalysis(Report(&*it) << "value cannot be used outside the loop");
+ return false;
+ }
+
+@@ -4009,7 +4025,7 @@
+ BE = TheLoop->block_end(); B != BE; ++B)
+ for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
+ I != IE; ++I)
+- if (I->getType()->isPointerTy() && isConsecutivePtr(I))
++ if (I->getType()->isPointerTy() && isConsecutivePtr(&*I))
+ Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
+
+ while (Worklist.size()) {
+@@ -4800,7 +4816,7 @@
+ if (it->mayWriteToMemory()) {
+ StoreInst *St = dyn_cast<StoreInst>(it);
+ if (!St) {
+- emitAnalysis(Report(it) << "instruction cannot be vectorized");
++ emitAnalysis(Report(&*it) << "instruction cannot be vectorized");
+ return false;
+ }
+ if (!St->isSimple() && !IsAnnotatedParallel) {
+@@ -5543,7 +5559,7 @@
+ Type *T = it->getType();
+
+ // Ignore ephemeral values.
+- if (EphValues.count(it))
++ if (EphValues.count(&*it))
+ continue;
+
+ // Only examine Loads, Stores and PHINodes.
+@@ -5562,7 +5578,7 @@
+ // Ignore loaded pointer types and stored pointer types that are not
+ // consecutive. However, we do want to take consecutive stores/loads of
+ // pointer vectors into account.
+- if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
++ if (T->isPointerTy() && !isConsecutiveLoadOrStore(&*it))
+ continue;
+
+ MaxWidth = std::max(MaxWidth,
+@@ -5765,7 +5781,7 @@
+ R.NumInstructions += (*bb)->size();
+ for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
+ ++it) {
+- Instruction *I = it;
++ Instruction *I = &*it;
+ IdxToInstr[Index++] = I;
+
+ // Save the end location of each USE.
+@@ -5853,10 +5869,10 @@
+ continue;
+
+ // Ignore ephemeral values.
+- if (EphValues.count(it))
++ if (EphValues.count(&*it))
+ continue;
+
+- unsigned C = getInstructionCost(it, VF);
++ unsigned C = getInstructionCost(&*it, VF);
+
+ // Check if we should override the cost.
+ if (ForceTargetInstructionCost.getNumOccurrences() > 0)
+@@ -6230,19 +6246,12 @@
+ // Create a new entry in the WidenMap and initialize it to Undef or Null.
+ VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
+
+- Instruction *InsertPt = Builder.GetInsertPoint();
+- BasicBlock *IfBlock = Builder.GetInsertBlock();
+- BasicBlock *CondBlock = nullptr;
+-
+ VectorParts Cond;
+- Loop *VectorLp = nullptr;
+ if (IfPredicateStore) {
+ assert(Instr->getParent()->getSinglePredecessor() &&
+ "Only support single predecessor blocks");
+ Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
+ Instr->getParent());
+- VectorLp = LI->getLoopFor(IfBlock);
+- assert(VectorLp && "Must have a loop for this block");
+ }
+
+ // For each vector unroll 'part':
+@@ -6257,11 +6266,6 @@
+ Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
+ Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
+ ConstantInt::get(Cond[Part]->getType(), 1));
+- CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
+- LoopVectorBody.push_back(CondBlock);
+- VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
+- // Update Builder with newly created basic block.
+- Builder.SetInsertPoint(InsertPt);
+ }
+
+ Instruction *Cloned = Instr->clone();
+@@ -6282,16 +6286,9 @@
+ VecResults[Part] = Cloned;
+
+ // End if-block.
+- if (IfPredicateStore) {
+- BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
+- LoopVectorBody.push_back(NewIfBlock);
+- VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
+- Builder.SetInsertPoint(InsertPt);
+- Instruction *OldBr = IfBlock->getTerminator();
+- BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
+- OldBr->eraseFromParent();
+- IfBlock = NewIfBlock;
+- }
++ if (IfPredicateStore)
++ PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned),
++ Cmp));
+ }
+ }
+
+--- lib/Transforms/Vectorize/SLPVectorizer.cpp 2015-02-12 09:51:17.000000000 -0800
++++ lib/Transforms/Vectorize/SLPVectorizer.cpp 2015-12-06 11:52:23.656576722 -0800
+@@ -1742,7 +1742,8 @@
+ }
+
+ // Now find the sequence of instructions between PrevInst and Inst.
+- BasicBlock::reverse_iterator InstIt(Inst), PrevInstIt(PrevInst);
++ BasicBlock::reverse_iterator InstIt(Inst->getIterator()),
++ PrevInstIt(PrevInst->getIterator());
+ --PrevInstIt;
+ while (InstIt != PrevInstIt) {
+ if (PrevInstIt == PrevInst->getParent()->rend()) {
+@@ -1890,7 +1891,7 @@
+
+ void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
+ Instruction *VL0 = cast<Instruction>(VL[0]);
+- BasicBlock::iterator NextInst = VL0;
++ BasicBlock::iterator NextInst(VL0);
+ ++NextInst;
+ Builder.SetInsertPoint(VL0->getParent(), NextInst);
+ Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
+@@ -2346,7 +2347,7 @@
+ scheduleBlock(BSIter.second.get());
+ }
+
+- Builder.SetInsertPoint(F->getEntryBlock().begin());
++ Builder.SetInsertPoint(&F->getEntryBlock().front());
+ vectorizeTree(&VectorizableTree[0]);
+
+ DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
+@@ -2391,7 +2392,7 @@
+ User->replaceUsesOfWith(Scalar, Ex);
+ }
+ } else {
+- Builder.SetInsertPoint(F->getEntryBlock().begin());
++ Builder.SetInsertPoint(&F->getEntryBlock().front());
+ Value *Ex = Builder.CreateExtractElement(Vec, Lane);
+ CSEBlocks.insert(&F->getEntryBlock());
+ User->replaceUsesOfWith(Scalar, Ex);
+@@ -2500,7 +2501,9 @@
+ BasicBlock *BB = (*I)->getBlock();
+ // For all instructions in blocks containing gather sequences:
+ for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
+- Instruction *In = it++;
++ Instruction *In = &*it;
++ ++it;
++
+ if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
+ continue;
+
+@@ -2648,7 +2651,7 @@
+ }
+ // Search up and down at the same time, because we don't know if the new
+ // instruction is above or below the existing scheduling region.
+- BasicBlock::reverse_iterator UpIter(ScheduleStart);
++ BasicBlock::reverse_iterator UpIter(ScheduleStart->getIterator());
+ BasicBlock::reverse_iterator UpperEnd = BB->rend();
+ BasicBlock::iterator DownIter(ScheduleEnd);
+ BasicBlock::iterator LowerEnd = BB->end();
+@@ -2860,7 +2863,8 @@
+ Instruction *pickedInst = BundleMember->Inst;
+ if (LastScheduledInst->getNextNode() != pickedInst) {
+ BS->BB->getInstList().remove(pickedInst);
+- BS->BB->getInstList().insert(LastScheduledInst, pickedInst);
++ BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
++ pickedInst);
+ }
+ LastScheduledInst = pickedInst;
+ BundleMember = BundleMember->NextInBundle;
+@@ -3243,8 +3247,8 @@
+ Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
+ unsigned VecIdx = 0;
+ for (auto &V : BuildVectorSlice) {
+- IRBuilder<true, NoFolder> Builder(
+- ++BasicBlock::iterator(InsertAfter));
++ IRBuilder<true, NoFolder> Builder(InsertAfter->getParent(),
++ ++BasicBlock::iterator(InsertAfter));
+ InsertElementInst *IE = cast<InsertElementInst>(V);
+ Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement(
+ VectorizedRoot, Builder.getInt32(VecIdx++)));
+@@ -3695,10 +3699,10 @@
+
+ for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
+ // We may go through BB multiple times so skip the one we have checked.
+- if (!VisitedInstrs.insert(it).second)
++ if (!VisitedInstrs.insert(&*it).second)
+ continue;
+
+- if (isa<DbgInfoIntrinsic>(it))
++ if (isa<DbgInfoIntrinsic>(&*it))
+ continue;
+
+ // Try to vectorize reductions that use PHINodes.
+--- tools/bugpoint/CrashDebugger.cpp 2014-08-26 10:19:03.000000000 -0700
++++ tools/bugpoint/CrashDebugger.cpp 2015-12-08 17:47:24.061167860 -0800
+@@ -148,7 +148,7 @@
+ // playing with...
+ for (Module::global_iterator I = M->global_begin(), E = M->global_end();
+ I != E; ++I)
+- if (I->hasInitializer() && !GVSet.count(I)) {
++ if (I->hasInitializer() && !GVSet.count(&*I)) {
+ I->setInitializer(nullptr);
+ I->setLinkage(GlobalValue::ExternalLinkage);
+ }
+@@ -222,8 +222,8 @@
+ // Loop over and delete any functions which we aren't supposed to be playing
+ // with...
+ for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
+- if (!I->isDeclaration() && !Functions.count(I))
+- DeleteFunctionBody(I);
++ if (!I->isDeclaration() && !Functions.count(&*I))
++ DeleteFunctionBody(&*I);
+
+ // Try running the hacked up program...
+ if (TestFn(BD, M)) {
+@@ -289,11 +289,12 @@
+ // Loop over and delete any hack up any blocks that are not listed...
+ for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
+ for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
+- if (!Blocks.count(BB) && BB->getTerminator()->getNumSuccessors()) {
++ if (!Blocks.count(&*BB) && BB->getTerminator()->getNumSuccessors()) {
+ // Loop over all of the successors of this block, deleting any PHI nodes
+ // that might include it.
+- for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
+- (*SI)->removePredecessor(BB);
++ for (succ_iterator SI = succ_begin(&*BB), E = succ_end(&*BB);
++ SI != E; ++SI)
++ (*SI)->removePredecessor(&*BB);
+
+ TerminatorInst *BBTerm = BB->getTerminator();
+
+@@ -302,7 +303,7 @@
+
+ // Replace the old terminator instruction.
+ BB->getInstList().pop_back();
+- new UnreachableInst(BB->getContext(), BB);
++ new UnreachableInst(BB->getContext(), &*BB);
+ }
+
+ // The CFG Simplifier pass may delete one of the basic blocks we are
+@@ -397,7 +398,8 @@
+ for (Module::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
+ for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI)
+ for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E;) {
+- Instruction *Inst = I++;
++ Instruction *Inst = &*I;
++ ++I;
+ if (!Instructions.count(Inst) && !isa<TerminatorInst>(Inst) &&
+ !isa<LandingPadInst>(Inst)) {
+ if (!Inst->getType()->isVoidTy())
+@@ -468,7 +470,7 @@
+ for (Module::global_iterator I = BD.getProgram()->global_begin(),
+ E = BD.getProgram()->global_end(); I != E; ++I)
+ if (I->hasInitializer())
+- GVs.push_back(I);
++ GVs.push_back(&*I);
+
+ if (GVs.size() > 1 && !BugpointIsInterrupted) {
+ outs() << "\n*** Attempting to reduce the number of global "
+@@ -491,7 +493,7 @@
+ for (Module::iterator I = BD.getProgram()->begin(),
+ E = BD.getProgram()->end(); I != E; ++I)
+ if (!I->isDeclaration())
+- Functions.push_back(I);
++ Functions.push_back(&*I);
+
+ if (Functions.size() > 1 && !BugpointIsInterrupted) {
+ outs() << "\n*** Attempting to reduce the number of functions "
+@@ -511,10 +513,11 @@
+ //
+ if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
+ std::vector<const BasicBlock*> Blocks;
+- for (Module::const_iterator I = BD.getProgram()->begin(),
+- E = BD.getProgram()->end(); I != E; ++I)
+- for (Function::const_iterator FI = I->begin(), E = I->end(); FI !=E; ++FI)
+- Blocks.push_back(FI);
++ for (Function &F : *BD.getProgram()) {
++ for (BasicBlock &BB : F)
++ Blocks.push_back(&BB);
++ }
++
+ unsigned OldSize = Blocks.size();
+ ReduceCrashingBlocks(BD, TestFn).reduceList(Blocks, Error);
+ if (Blocks.size() < OldSize)
+@@ -525,14 +528,11 @@
+ // cases with large basic blocks where the problem is at one end.
+ if (!BugpointIsInterrupted) {
+ std::vector<const Instruction*> Insts;
+- for (Module::const_iterator MI = BD.getProgram()->begin(),
+- ME = BD.getProgram()->end(); MI != ME; ++MI)
+- for (Function::const_iterator FI = MI->begin(), FE = MI->end(); FI != FE;
+- ++FI)
+- for (BasicBlock::const_iterator I = FI->begin(), E = FI->end();
+- I != E; ++I)
+- if (!isa<TerminatorInst>(I))
+- Insts.push_back(I);
++ for (const Function &F : *BD.getProgram())
++ for (const BasicBlock &BB : F)
++ for (const Instruction &I : BB)
++ if (!isa<TerminatorInst>(&I))
++ Insts.push_back(&I);
+
+ ReduceCrashingInstructions(BD, TestFn).reduceList(Insts, Error);
+ }
+@@ -577,7 +577,7 @@
+
+ outs() << "Checking instruction: " << *I;
+ std::unique_ptr<Module> M =
+- BD.deleteInstructionFromProgram(I, Simplification);
++ BD.deleteInstructionFromProgram(&*I, Simplification);
+
+ // Find out if the pass still crashes on this pass...
+ if (TestFn(BD, M.get())) {
+--- tools/bugpoint/ExtractFunction.cpp 2014-08-26 10:19:03.000000000 -0700
++++ tools/bugpoint/ExtractFunction.cpp 2015-12-08 17:53:34.720329668 -0800
+@@ -100,7 +100,7 @@
+
+ BasicBlock::iterator RI = RBI->begin(); // Get iterator to corresponding inst
+ std::advance(RI, std::distance(PBB->begin(), BasicBlock::const_iterator(I)));
+- Instruction *TheInst = RI; // Got the corresponding instruction!
++ Instruction *TheInst = &*RI; // Got the corresponding instruction!
+
+ // If this instruction produces a value, replace any users with null values
+ if (!TheInst->getType()->isVoidTy())
+@@ -307,15 +307,15 @@
+
+ // Remove the Safe functions from the Test module
+ for (Module::iterator I = New->begin(), E = New->end(); I != E; ++I)
+- if (!TestFunctions.count(I))
+- DeleteFunctionBody(I);
++ if (!TestFunctions.count(&*I))
++ DeleteFunctionBody(&*I);
+
+
+ // Try to split the global initializers evenly
+ for (Module::global_iterator I = M->global_begin(), E = M->global_end();
+ I != E; ++I) {
+- GlobalVariable *GV = cast<GlobalVariable>(NewVMap[I]);
+- if (Function *TestFn = globalInitUsesExternalBA(I)) {
++ GlobalVariable *GV = cast<GlobalVariable>(NewVMap[&*I]);
++ if (Function *TestFn = globalInitUsesExternalBA(&*I)) {
+ if (Function *SafeFn = globalInitUsesExternalBA(GV)) {
+ errs() << "*** Error: when reducing functions, encountered "
+ "the global '";
+--- tools/bugpoint/Miscompilation.cpp 2014-10-27 17:24:16.000000000 -0700
++++ tools/bugpoint/Miscompilation.cpp 2015-12-08 17:55:31.425007898 -0800
+@@ -550,7 +550,7 @@
+ for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
+ for (Function::iterator I = MiscompiledFunctions[i]->begin(),
+ E = MiscompiledFunctions[i]->end(); I != E; ++I)
+- Blocks.push_back(I);
++ Blocks.push_back(&*I);
+
+ // Use the list reducer to identify blocks that can be extracted without
+ // obscuring the bug. The Blocks list will end up containing blocks that must
+@@ -634,7 +634,7 @@
+ Module *Prog = BD.getProgram();
+ for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
+ if (!I->isDeclaration())
+- MiscompiledFunctions.push_back(I);
++ MiscompiledFunctions.push_back(&*I);
+
+ // Do the reduction...
+ if (!BugpointIsInterrupted)
+@@ -806,7 +806,7 @@
+ I = newMain->arg_begin(), E = newMain->arg_end(),
+ OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
+ I->setName(OI->getName()); // Copy argument names from oldMain
+- args.push_back(I);
++ args.push_back(&*I);
+ }
+
+ // Call the old main function and return its result
+@@ -910,7 +910,7 @@
+ std::vector<Value*> Args;
+ for (Function::arg_iterator i = FuncWrapper->arg_begin(),
+ e = FuncWrapper->arg_end(); i != e; ++i)
+- Args.push_back(i);
++ Args.push_back(&*i);
+
+ // Pass on the arguments to the real function, return its result
+ if (F->getReturnType()->isVoidTy()) {
+--- tools/clang/include/clang/Analysis/CFG.h 2015-10-05 11:01:32.409005315 -0700
++++ tools/clang/include/clang/Analysis/CFG.h 2015-12-08 08:12:46.482439723 -0800
+@@ -322,7 +322,7 @@
+ Stmt &operator*() { return *getStmt(); }
+ const Stmt &operator*() const { return *getStmt(); }
+
+- LLVM_EXPLICIT operator bool() const { return getStmt(); }
++ explicit operator bool() const { return getStmt(); }
+ };
+
+ /// CFGBlock - Represents a single basic block in a source-level CFG.
+@@ -432,7 +432,7 @@
+ public:
+ /// Construct an AdjacentBlock with a possibly unreachable block.
+ AdjacentBlock(CFGBlock *B, bool IsReachable);
+-
++
+ /// Construct an AdjacentBlock with a reachable block and an alternate
+ /// unreachable block.
+ AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock);
+@@ -694,7 +694,7 @@
+ iterator beginAutomaticObjDtorsInsert(iterator I, size_t Cnt,
+ BumpVectorContext &C) {
+ return iterator(Elements.insert(I.base(), Cnt,
+- CFGAutomaticObjDtor(nullptr, 0), C));
++ CFGAutomaticObjDtor(nullptr, nullptr), C));
+ }
+ iterator insertAutomaticObjDtor(iterator I, VarDecl *VD, Stmt *S) {
+ *I = CFGAutomaticObjDtor(VD, S);
+@@ -767,7 +767,7 @@
+ /// (not a pointer to CFGBlock).
+ class graph_iterator {
+ public:
+- typedef const CFGBlock value_type;
++ typedef CFGBlock value_type;
+ typedef value_type& reference;
+ typedef value_type* pointer;
+ typedef BumpVector<CFGBlock*>::iterator ImplTy;
+--- tools/clang/lib/Frontend/Rewrite/InclusionRewriter.cpp 2015-10-05 11:01:32.364932580 -0700
++++ tools/clang/lib/Frontend/Rewrite/InclusionRewriter.cpp 2015-10-12 22:15:59.378584335 -0700
+@@ -285,16 +285,11 @@
+ do {
+ DirectiveLex.LexFromRawLexer(DirectiveToken);
+ } while (!DirectiveToken.is(tok::eod) && DirectiveToken.isNot(tok::eof));
++
+ if (&FromFile == PredefinesBuffer) {
+ // OutputContentUpTo() would not output anything anyway.
+ return;
+ }
+- OS << "#if 0 /* expanded by -frewrite-includes */" << MainEOL;
+- OutputContentUpTo(FromFile, NextToWrite,
+- SM.getFileOffset(DirectiveToken.getLocation()) +
+- DirectiveToken.getLength(),
+- LocalEOL, Line, true);
+- OS << "#endif /* expanded by -frewrite-includes */" << MainEOL;
+ }
+
+ /// Find the next identifier in the pragma directive specified by \p RawToken.
+--- tools/clang/lib/StaticAnalyzer/Core/BugReporter.cpp 2015-10-05 11:01:32.334095518 -0700
++++ tools/clang/lib/StaticAnalyzer/Core/BugReporter.cpp 2015-12-08 09:02:55.503942822 -0800
+@@ -3295,11 +3295,11 @@
+ // post-dominated by a sink, simply add all the nodes in the equivalence class
+ // to 'Nodes'. Any of the reports will serve as a "representative" report.
+ if (!BT.isSuppressOnSink()) {
+- BugReport *R = I;
++ BugReport *R = &*I;
+ for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
+ const ExplodedNode *N = I->getErrorNode();
+ if (N) {
+- R = I;
++ R = &*I;
+ bugReports.push_back(R);
+ }
+ }
+@@ -3325,35 +3325,35 @@
+ }
+ // No successors? By definition this nodes isn't post-dominated by a sink.
+ if (errorNode->succ_empty()) {
+- bugReports.push_back(I);
++ bugReports.push_back(&*I);
+ if (!exampleReport)
+- exampleReport = I;
++ exampleReport = &*I;
+ continue;
+ }
+
+ // At this point we know that 'N' is not a sink and it has at least one
+- // successor. Use a DFS worklist to find a non-sink end-of-path node.
++ // successor. Use a DFS worklist to find a non-sink end-of-path node.
+ typedef FRIEC_WLItem WLItem;
+ typedef SmallVector<WLItem, 10> DFSWorkList;
+ llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
+-
++
+ DFSWorkList WL;
+ WL.push_back(errorNode);
+ Visited[errorNode] = 1;
+-
++
+ while (!WL.empty()) {
+ WLItem &WI = WL.back();
+ assert(!WI.N->succ_empty());
+-
++
+ for (; WI.I != WI.E; ++WI.I) {
+- const ExplodedNode *Succ = *WI.I;
++ const ExplodedNode *Succ = *WI.I;
+ // End-of-path node?
+ if (Succ->succ_empty()) {
+ // If we found an end-of-path node that is not a sink.
+ if (!Succ->isSink()) {
+- bugReports.push_back(I);
++ bugReports.push_back(&*I);
+ if (!exampleReport)
+- exampleReport = I;
++ exampleReport = &*I;
+ WL.clear();
+ break;
+ }
+--- tools/llvm-diff/DifferenceEngine.cpp 2014-07-21 10:06:51.000000000 -0700
++++ tools/llvm-diff/DifferenceEngine.cpp 2015-12-08 13:51:00.260552197 -0800
+@@ -599,7 +599,7 @@
+ TerminatorInst *RTerm = RStart->getParent()->getTerminator();
+ if (isa<BranchInst>(LTerm) && isa<InvokeInst>(RTerm)) {
+ if (cast<BranchInst>(LTerm)->isConditional()) return;
+- BasicBlock::iterator I = LTerm;
++ BasicBlock::iterator I = LTerm->getIterator();
+ if (I == LStart->getParent()->begin()) return;
+ --I;
+ if (!isa<CallInst>(*I)) return;
+@@ -612,7 +612,7 @@
+ tryUnify(LTerm->getSuccessor(0), RInvoke->getNormalDest());
+ } else if (isa<InvokeInst>(LTerm) && isa<BranchInst>(RTerm)) {
+ if (cast<BranchInst>(RTerm)->isConditional()) return;
+- BasicBlock::iterator I = RTerm;
++ BasicBlock::iterator I = RTerm->getIterator();
+ if (I == RStart->getParent()->begin()) return;
+ --I;
+ if (!isa<CallInst>(*I)) return;
+--- tools/llvm-stress/llvm-stress.cpp 2014-08-25 11:16:47.000000000 -0700
++++ tools/llvm-stress/llvm-stress.cpp 2015-12-08 17:59:08.743284003 -0800
+@@ -622,7 +622,7 @@
+ // Consider arguments as legal values.
+ for (Function::arg_iterator it = F->arg_begin(), e = F->arg_end();
+ it != e; ++it)
+- PT.push_back(it);
++ PT.push_back(&*it);
+
+ // List of modifiers which add new random instructions.
+ std::vector<Modifier*> Modifiers;
+@@ -663,16 +663,15 @@
+ for (BasicBlock::iterator it = F->begin()->begin(),
+ e = F->begin()->end(); it != e; ++it) {
+ if (it->getType() == IntegerType::getInt1Ty(F->getContext()))
+- BoolInst.push_back(it);
++ BoolInst.push_back(&*it);
+ }
+
+ std::random_shuffle(BoolInst.begin(), BoolInst.end(), R);
+
+- for (std::vector<Instruction*>::iterator it = BoolInst.begin(),
+- e = BoolInst.end(); it != e; ++it) {
+- Instruction *Instr = *it;
++
++ for (auto *Instr : BoolInst) {
+ BasicBlock *Curr = Instr->getParent();
+- BasicBlock::iterator Loc= Instr;
++ BasicBlock::iterator Loc = Instr->getIterator();
+ BasicBlock *Next = Curr->splitBasicBlock(Loc, "CF");
+ Instr->moveBefore(Curr->getTerminator());
+ if (Curr != &F->getEntryBlock()) {
+--- unittests/ADT/ilistTest.cpp 2014-06-08 15:29:17.000000000 -0700
++++ unittests/ADT/ilistTest.cpp 2016-01-23 11:05:55.000000000 -0800
+@@ -80,7 +80,7 @@
+ // List with contents.
+ List.push_back(1);
+ ASSERT_EQ(1u, List.size());
+- Node *N = List.begin();
++ Node *N = &*List.begin();
+ EXPECT_EQ(1, N->Value);
+ List.clearAndLeakNodesUnsafely();
+ EXPECT_EQ(0u, List.size());
+--- unittests/Analysis/CFGTest.cpp 2014-08-19 09:58:54.000000000 -0700
++++ unittests/Analysis/CFGTest.cpp 2016-01-23 11:08:10.000000000 -0800
+@@ -378,7 +378,7 @@
+ TEST_F(IsPotentiallyReachableTest, ModifyTest) {
+ ParseAssembly(BranchInsideLoopIR);
+
+- succ_iterator S = succ_begin(++M->getFunction("test")->begin());
++ succ_iterator S = succ_begin(&*++M->getFunction("test")->begin());
+ BasicBlock *OldBB = S[0];
+ S[0] = S[1];
+ ExpectPath(false);
+--- unittests/ExecutionEngine/MCJIT/MCJITTestBase.h 2014-12-02 16:51:19.000000000 -0800
++++ unittests/ExecutionEngine/MCJIT/MCJITTestBase.h 2016-01-23 11:13:10.000000000 -0800
+@@ -71,8 +71,8 @@
+ SmallVector<Value*, 1> CallArgs;
+
+ Function::arg_iterator arg_iter = Result->arg_begin();
+- for(;arg_iter != Result->arg_end(); ++arg_iter)
+- CallArgs.push_back(arg_iter);
++ for (Argument &A : Result->args())
++ CallArgs.push_back(&A);
+
+ Value *ReturnCode = Builder.CreateCall(Callee, CallArgs);
+ Builder.CreateRet(ReturnCode);
+@@ -98,8 +98,8 @@
+ Function *Result = startFunction<int32_t(int32_t, int32_t)>(M, Name);
+
+ Function::arg_iterator args = Result->arg_begin();
+- Value *Arg1 = args;
+- Value *Arg2 = ++args;
++ Value *Arg1 = &*args;
++ Value *Arg2 = &*++args;
+ Value *AddResult = Builder.CreateAdd(Arg1, Arg2);
+
+ endFunctionWithRet(Result, AddResult);
+@@ -170,7 +170,7 @@
+ BasicBlock *RecursiveCase = BasicBlock::Create(Context, "", Result);
+
+ // if (num == 0)
+- Value *Param = Result->arg_begin();
++ Value *Param = &*Result->arg_begin();
+ Value *Zero = ConstantInt::get(Context, APInt(32, 0));
+ Builder.CreateCondBr(Builder.CreateICmpEQ(Param, Zero),
+ BaseCase, RecursiveCase);
+--- unittests/IR/DominatorTreeTest.cpp 2014-08-19 09:58:54.000000000 -0700
++++ unittests/IR/DominatorTreeTest.cpp 2016-01-23 11:18:36.000000000 -0800
+@@ -31,29 +31,29 @@
+ PostDominatorTree *PDT = &getAnalysis<PostDominatorTree>();
+ Function::iterator FI = F.begin();
+
+- BasicBlock *BB0 = FI++;
++ BasicBlock *BB0 = &*FI++;
+ BasicBlock::iterator BBI = BB0->begin();
+- Instruction *Y1 = BBI++;
+- Instruction *Y2 = BBI++;
+- Instruction *Y3 = BBI++;
++ Instruction *Y1 = &*BBI++;
++ Instruction *Y2 = &*BBI++;
++ Instruction *Y3 = &*BBI++;
+
+- BasicBlock *BB1 = FI++;
++ BasicBlock *BB1 = &*FI++;
+ BBI = BB1->begin();
+- Instruction *Y4 = BBI++;
++ Instruction *Y4 = &*BBI++;
+
+- BasicBlock *BB2 = FI++;
++ BasicBlock *BB2 = &*FI++;
+ BBI = BB2->begin();
+- Instruction *Y5 = BBI++;
++ Instruction *Y5 = &*BBI++;
+
+- BasicBlock *BB3 = FI++;
++ BasicBlock *BB3 = &*FI++;
+ BBI = BB3->begin();
+- Instruction *Y6 = BBI++;
+- Instruction *Y7 = BBI++;
++ Instruction *Y6 = &*BBI++;
++ Instruction *Y7 = &*BBI++;
+
+- BasicBlock *BB4 = FI++;
++ BasicBlock *BB4 = &*FI++;
+ BBI = BB4->begin();
+- Instruction *Y8 = BBI++;
+- Instruction *Y9 = BBI++;
++ Instruction *Y8 = &*BBI++;
++ Instruction *Y9 = &*BBI++;
+
+ // Reachability
+ EXPECT_TRUE(DT->isReachableFromEntry(BB0));
+--- unittests/IR/IRBuilderTest.cpp 2014-09-02 13:03:00.000000000 -0700
++++ unittests/IR/IRBuilderTest.cpp 2016-01-23 11:19:43.000000000 -0800
+@@ -280,7 +280,7 @@
+ {
+ IRBuilder<>::InsertPointGuard Guard(Builder);
+ Builder.SetInsertPoint(cast<Instruction>(F));
+- EXPECT_EQ(F, Builder.GetInsertPoint());
++ EXPECT_EQ(F, &*Builder.GetInsertPoint());
+ }
+
+ EXPECT_EQ(BB->end(), Builder.GetInsertPoint());
+--- unittests/IR/LegacyPassManagerTest.cpp 2014-09-10 14:27:43.000000000 -0700
++++ unittests/IR/LegacyPassManagerTest.cpp 2016-01-23 11:21:26.000000000 -0800
+@@ -521,7 +521,7 @@
+ // Function: test4 (func_test4)
+ {
+ Function::arg_iterator args = func_test4->arg_begin();
+- Value* int1_f = args++;
++ Value* int1_f = &*args++;
+ int1_f->setName("f");
+
+ BasicBlock* label_entry_11 = BasicBlock::Create(getGlobalContext(), "entry",func_test4,nullptr);
+--- unittests/IR/ValueTest.cpp 2014-10-23 07:45:19.000000000 -0700
++++ unittests/IR/ValueTest.cpp 2016-01-23 11:23:38.000000000 -0800
+@@ -38,9 +38,9 @@
+
+ Function *F = M->getFunction("f");
+
+- EXPECT_FALSE(F->isUsedInBasicBlock(F->begin()));
+- EXPECT_TRUE((++F->arg_begin())->isUsedInBasicBlock(F->begin()));
+- EXPECT_TRUE(F->arg_begin()->isUsedInBasicBlock(F->begin()));
++ EXPECT_FALSE(F->isUsedInBasicBlock(&F->front()));
++ EXPECT_TRUE((++F->arg_begin())->isUsedInBasicBlock(&F->front()));
++ EXPECT_TRUE(F->arg_begin()->isUsedInBasicBlock(&F->front()));
+ }
+
+ TEST(GlobalTest, CreateAddressSpace) {
+--- unittests/Linker/LinkModulesTest.cpp 2015-01-14 03:23:27.000000000 -0800
++++ unittests/Linker/LinkModulesTest.cpp 2016-01-23 11:25:17.000000000 -0800
+@@ -73,7 +73,7 @@
+
+ std::vector<Value *> GEPIndices;
+ GEPIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ctx), 0));
+- GEPIndices.push_back(F->arg_begin());
++ GEPIndices.push_back(&*F->arg_begin());
+
+ Value *GEP = Builder.CreateGEP(GV, GEPIndices, "switch.gep");
+ Value *Load = Builder.CreateLoad(GEP, "switch.load");
+--- unittests/Support/Makefile 2013-08-01 11:42:28.000000000 -0700
++++ unittests/Support/Makefile 2016-01-27 11:20:22.000000000 -0800
+@@ -13,3 +13,7 @@
+
+ include $(LEVEL)/Makefile.config
+ include $(LLVM_SRC_ROOT)/unittests/Makefile.unittest
++
++C.Flags += -DALIAS_WITH_ARGUMENT_TESTS_ARE_BROKEN
++CXX.Flags += -DALIAS_WITH_ARGUMENT_TESTS_ARE_BROKEN
++
+--- unittests/Transforms/Utils/Cloning.cpp 2015-01-14 03:23:27.000000000 -0800
++++ unittests/Transforms/Utils/Cloning.cpp 2016-01-23 11:29:52.000000000 -0800
+@@ -165,7 +165,7 @@
+
+ Attribute::AttrKind AK[] = { Attribute::NoCapture };
+ AttributeSet AS = AttributeSet::get(context, 0, AK);
+- Argument *A = F1->arg_begin();
++ Argument *A = &*F1->arg_begin();
+ A->addAttr(AS);
+
+ SmallVector<ReturnInst*, 4> Returns;
+@@ -193,7 +193,7 @@
+
+ SmallVector<ReturnInst*, 4> Returns;
+ ValueToValueMapTy VMap;
+- VMap[F1->arg_begin()] = F2->arg_begin();
++ VMap[&*F1->arg_begin()] = &*F2->arg_begin();
+
+ CloneFunctionInto(F2, F1, VMap, false, Returns);
+ EXPECT_EQ(CallingConv::Cold, F2->getCallingConv());
+--- unittests/Transforms/Utils/IntegerDivision.cpp 2013-11-18 22:54:19.000000000 -0800
++++ unittests/Transforms/Utils/IntegerDivision.cpp 2016-01-23 11:32:46.000000000 -0800
+@@ -35,8 +35,8 @@
+ Builder.SetInsertPoint(BB);
+
+ Function::arg_iterator AI = F->arg_begin();
+- Value *A = AI++;
+- Value *B = AI++;
++ Value *A = &*AI++;
++ Value *B = &*AI++;
+
+ Value *Div = Builder.CreateSDiv(A, B);
+ EXPECT_TRUE(BB->front().getOpcode() == Instruction::SDiv);
+@@ -65,8 +65,8 @@
+ Builder.SetInsertPoint(BB);
+
+ Function::arg_iterator AI = F->arg_begin();
+- Value *A = AI++;
+- Value *B = AI++;
++ Value *A = &*AI++;
++ Value *B = &*AI++;
+
+ Value *Div = Builder.CreateUDiv(A, B);
+ EXPECT_TRUE(BB->front().getOpcode() == Instruction::UDiv);
+@@ -95,8 +95,8 @@
+ Builder.SetInsertPoint(BB);
+
+ Function::arg_iterator AI = F->arg_begin();
+- Value *A = AI++;
+- Value *B = AI++;
++ Value *A = &*AI++;
++ Value *B = &*AI++;
+
+ Value *Rem = Builder.CreateSRem(A, B);
+ EXPECT_TRUE(BB->front().getOpcode() == Instruction::SRem);
+@@ -125,8 +125,8 @@
+ Builder.SetInsertPoint(BB);
+
+ Function::arg_iterator AI = F->arg_begin();
+- Value *A = AI++;
+- Value *B = AI++;
++ Value *A = &*AI++;
++ Value *B = &*AI++;
+
+ Value *Rem = Builder.CreateURem(A, B);
+ EXPECT_TRUE(BB->front().getOpcode() == Instruction::URem);
+@@ -156,8 +156,8 @@
+ Builder.SetInsertPoint(BB);
+
+ Function::arg_iterator AI = F->arg_begin();
+- Value *A = AI++;
+- Value *B = AI++;
++ Value *A = &*AI++;
++ Value *B = &*AI++;
+
+ Value *Div = Builder.CreateSDiv(A, B);
+ EXPECT_TRUE(BB->front().getOpcode() == Instruction::SDiv);
+@@ -186,8 +186,8 @@
+ Builder.SetInsertPoint(BB);
+
+ Function::arg_iterator AI = F->arg_begin();
+- Value *A = AI++;
+- Value *B = AI++;
++ Value *A = &*AI++;
++ Value *B = &*AI++;
+
+ Value *Div = Builder.CreateUDiv(A, B);
+ EXPECT_TRUE(BB->front().getOpcode() == Instruction::UDiv);
+@@ -216,8 +216,8 @@
+ Builder.SetInsertPoint(BB);
+
+ Function::arg_iterator AI = F->arg_begin();
+- Value *A = AI++;
+- Value *B = AI++;
++ Value *A = &*AI++;
++ Value *B = &*AI++;
+
+ Value *Rem = Builder.CreateSRem(A, B);
+ EXPECT_TRUE(BB->front().getOpcode() == Instruction::SRem);
+@@ -246,8 +246,8 @@
+ Builder.SetInsertPoint(BB);
+
+ Function::arg_iterator AI = F->arg_begin();
+- Value *A = AI++;
+- Value *B = AI++;
++ Value *A = &*AI++;
++ Value *B = &*AI++;
+
+ Value *Rem = Builder.CreateURem(A, B);
+ EXPECT_TRUE(BB->front().getOpcode() == Instruction::URem);