diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 45da8af51bb9cefa6312b8966bf6cd63a6dcc09e..0f178df1d18f8c46a2b06aa00667e81f3a1be32a 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -35,6 +35,10 @@ clang/lib/AST/Interp/ @tbaederr clang/test/AST/Interp/ @tbaederr +/clang/include/clang/CIR @lanza @bcardosolopes +/clang/lib/CIR @lanza @bcardosolopes +/clang/tools/cir-* @lanza @bcardosolopes + /lldb/ @JDevlieghere # MLIR Interfaces. diff --git a/bolt/include/bolt/Profile/DataAggregator.h b/bolt/include/bolt/Profile/DataAggregator.h index 84f76caae9dbb01ea38e59f5eb629e0492ddb800..f2fa59bcaa1a3ace0d96446bba629992700ea362 100644 --- a/bolt/include/bolt/Profile/DataAggregator.h +++ b/bolt/include/bolt/Profile/DataAggregator.h @@ -198,14 +198,8 @@ private: /// A trace is region of code executed between two LBR entries supplied in /// execution order. /// - /// Return true if the trace is valid, false otherwise. - bool - recordTrace(BinaryFunction &BF, const LBREntry &First, const LBREntry &Second, - uint64_t Count, - SmallVector, 16> &Branches) const; - /// Return a vector of offsets corresponding to a trace in a function - /// (see recordTrace() above). + /// if the trace is valid, std::nullopt otherwise. std::optional, 16>> getFallthroughsInTrace(BinaryFunction &BF, const LBREntry &First, const LBREntry &Second, uint64_t Count = 1) const; diff --git a/bolt/include/bolt/Rewrite/RewriteInstance.h b/bolt/include/bolt/Rewrite/RewriteInstance.h index 2561468a0f99af4d46c04f78aa3eff5d9dfbcb4a..41a92e7ba01e8495bc0a6b4329017d2f1e2c40fd 100644 --- a/bolt/include/bolt/Rewrite/RewriteInstance.h +++ b/bolt/include/bolt/Rewrite/RewriteInstance.h @@ -422,8 +422,13 @@ private: /// Section name used for extra BOLT code in addition to .text. static StringRef getBOLTTextSectionName() { return ".bolt.text"; } + /// Symbol markers for BOLT reserved area. + static StringRef getBOLTReservedStart() { return "__bolt_reserved_start"; } + static StringRef getBOLTReservedEnd() { return "__bolt_reserved_end"; } + /// Common section names. static StringRef getEHFrameSectionName() { return ".eh_frame"; } + static StringRef getEHFrameHdrSectionName() { return ".eh_frame_hdr"; } static StringRef getRelaDynSectionName() { return ".rela.dyn"; } /// FILE symbol name used for local fragments of global functions. @@ -493,6 +498,9 @@ private: /// Store all non-zero symbols in this map for a quick address lookup. std::map FileSymRefs; + /// FILE symbols used for disambiguating split function parents. + std::vector FileSymbols; + std::unique_ptr DebugInfoRewriter; std::unique_ptr BAT; diff --git a/bolt/include/bolt/Utils/NameResolver.h b/bolt/include/bolt/Utils/NameResolver.h index 2e3ac20a532d76f848ea48d865194f8348dc65ba..ccffa5633245ce4504e9bf4d7b4fc95d62e3c996 100644 --- a/bolt/include/bolt/Utils/NameResolver.h +++ b/bolt/include/bolt/Utils/NameResolver.h @@ -28,10 +28,23 @@ class NameResolver { static constexpr char Sep = '/'; public: - /// Return unique version of the \p Name in the form "Name". + /// Return the number of uniquified versions of a given \p Name. + uint64_t getUniquifiedNameCount(StringRef Name) const { + if (Counters.contains(Name)) + return Counters.at(Name); + return 0; + } + + /// Return unique version of the \p Name in the form "Name". + std::string getUniqueName(StringRef Name, const uint64_t ID) const { + return (Name + Twine(Sep) + Twine(ID)).str(); + } + + /// Register new version of \p Name and return unique version in the form + /// "Name". std::string uniquify(StringRef Name) { const uint64_t ID = ++Counters[Name]; - return (Name + Twine(Sep) + Twine(ID)).str(); + return getUniqueName(Name, ID); } /// For uniquified \p Name, return the original form (that may no longer be diff --git a/bolt/lib/Profile/DataAggregator.cpp b/bolt/lib/Profile/DataAggregator.cpp index 70e324cc0165bb969c6a63d8f9334b80fb8fbd6c..5108392c824c1073638c4dcbb4b870b61dc8d5f4 100644 --- a/bolt/lib/Profile/DataAggregator.cpp +++ b/bolt/lib/Profile/DataAggregator.cpp @@ -861,14 +861,17 @@ bool DataAggregator::doTrace(const LBREntry &First, const LBREntry &Second, return true; } -bool DataAggregator::recordTrace( - BinaryFunction &BF, const LBREntry &FirstLBR, const LBREntry &SecondLBR, - uint64_t Count, - SmallVector, 16> &Branches) const { +std::optional, 16>> +DataAggregator::getFallthroughsInTrace(BinaryFunction &BF, + const LBREntry &FirstLBR, + const LBREntry &SecondLBR, + uint64_t Count) const { + SmallVector, 16> Branches; + BinaryContext &BC = BF.getBinaryContext(); if (!BF.isSimple()) - return false; + return std::nullopt; assert(BF.hasCFG() && "can only record traces in CFG state"); @@ -877,13 +880,13 @@ bool DataAggregator::recordTrace( const uint64_t To = SecondLBR.From - BF.getAddress(); if (From > To) - return false; + return std::nullopt; const BinaryBasicBlock *FromBB = BF.getBasicBlockContainingOffset(From); const BinaryBasicBlock *ToBB = BF.getBasicBlockContainingOffset(To); if (!FromBB || !ToBB) - return false; + return std::nullopt; // Adjust FromBB if the first LBR is a return from the last instruction in // the previous block (that instruction should be a call). @@ -907,7 +910,7 @@ bool DataAggregator::recordTrace( // within the same basic block, e.g. when two call instructions are in the // same block. In this case we skip the processing. if (FromBB == ToBB) - return true; + return Branches; // Process blocks in the original layout order. BinaryBasicBlock *BB = BF.getLayout().getBlock(FromBB->getIndex()); @@ -921,7 +924,7 @@ bool DataAggregator::recordTrace( LLVM_DEBUG(dbgs() << "no fall-through for the trace:\n" << " " << FirstLBR << '\n' << " " << SecondLBR << '\n'); - return false; + return std::nullopt; } const MCInst *Instr = BB->getLastNonPseudoInstr(); @@ -945,20 +948,7 @@ bool DataAggregator::recordTrace( BI.Count += Count; } - return true; -} - -std::optional, 16>> -DataAggregator::getFallthroughsInTrace(BinaryFunction &BF, - const LBREntry &FirstLBR, - const LBREntry &SecondLBR, - uint64_t Count) const { - SmallVector, 16> Res; - - if (!recordTrace(BF, FirstLBR, SecondLBR, Count, Res)) - return std::nullopt; - - return Res; + return Branches; } bool DataAggregator::recordEntry(BinaryFunction &BF, uint64_t To, bool Mispred, diff --git a/bolt/lib/Rewrite/LinuxKernelRewriter.cpp b/bolt/lib/Rewrite/LinuxKernelRewriter.cpp index d96199e020d31a159c9505d846a3985d9df2223c..17077b4fa2487adfaf2c05a514fb48c750751d38 100644 --- a/bolt/lib/Rewrite/LinuxKernelRewriter.cpp +++ b/bolt/lib/Rewrite/LinuxKernelRewriter.cpp @@ -248,6 +248,9 @@ class LinuxKernelRewriter final : public MetadataRewriter { /// Update ORC data in the binary. Error rewriteORCTables(); + /// Validate written ORC tables after binary emission. + Error validateORCTables(); + /// Static call table handling. Error readStaticCalls(); Error rewriteStaticCalls(); @@ -358,6 +361,9 @@ public: if (Error E = updateStaticKeysJumpTablePostEmit()) return E; + if (Error E = validateORCTables()) + return E; + return Error::success(); } }; @@ -837,6 +843,32 @@ Error LinuxKernelRewriter::rewriteORCTables() { return Error::success(); } +Error LinuxKernelRewriter::validateORCTables() { + if (!ORCUnwindIPSection) + return Error::success(); + + const uint64_t IPSectionAddress = ORCUnwindIPSection->getAddress(); + DataExtractor IPDE = DataExtractor(ORCUnwindIPSection->getOutputContents(), + BC.AsmInfo->isLittleEndian(), + BC.AsmInfo->getCodePointerSize()); + DataExtractor::Cursor IPCursor(0); + uint64_t PrevIP = 0; + for (uint32_t Index = 0; Index < NumORCEntries; ++Index) { + const uint64_t IP = + IPSectionAddress + IPCursor.tell() + (int32_t)IPDE.getU32(IPCursor); + if (!IPCursor) + return createStringError(errc::executable_format_error, + "out of bounds while reading ORC IP table: %s", + toString(IPCursor.takeError()).c_str()); + + assert(IP >= PrevIP && "Unsorted ORC table detected"); + (void)PrevIP; + PrevIP = IP; + } + + return Error::success(); +} + /// The static call site table is created by objtool and contains entries in the /// following format: /// diff --git a/bolt/lib/Rewrite/RewriteInstance.cpp b/bolt/lib/Rewrite/RewriteInstance.cpp index 3cf0e749f9d6671fba629e5a97120ce2bc7852f3..23f79e3c135a78f7b7f82e25d91c8987f31775b6 100644 --- a/bolt/lib/Rewrite/RewriteInstance.cpp +++ b/bolt/lib/Rewrite/RewriteInstance.cpp @@ -840,6 +840,7 @@ void RewriteInstance::discoverFileObjects() { continue; if (cantFail(Symbol.getType()) == SymbolRef::ST_File) { + FileSymbols.emplace_back(Symbol); StringRef Name = cantFail(std::move(NameOrError), "cannot get symbol name for file"); // Ignore Clang LTO artificial FILE symbol as it is not always generated, @@ -1062,6 +1063,11 @@ void RewriteInstance::discoverFileObjects() { continue; } + if (SymName == getBOLTReservedStart() || SymName == getBOLTReservedEnd()) { + registerName(SymbolSize); + continue; + } + LLVM_DEBUG(dbgs() << "BOLT-DEBUG: considering symbol " << UniqueName << " for function\n"); @@ -1340,6 +1346,7 @@ void RewriteInstance::discoverFileObjects() { } registerFragments(); + FileSymbols.clear(); } Error RewriteInstance::discoverRtFiniAddress() { @@ -1417,50 +1424,134 @@ void RewriteInstance::registerFragments() { if (!BC->HasSplitFunctions) return; + // Process fragments with ambiguous parents separately as they are typically a + // vanishing minority of cases and require expensive symbol table lookups. + std::vector> AmbiguousFragments; for (auto &BFI : BC->getBinaryFunctions()) { BinaryFunction &Function = BFI.second; if (!Function.isFragment()) continue; - unsigned ParentsFound = 0; for (StringRef Name : Function.getNames()) { - StringRef BaseName, Suffix; - std::tie(BaseName, Suffix) = Name.split('/'); + StringRef BaseName = NR.restore(Name); + const bool IsGlobal = BaseName == Name; const size_t ColdSuffixPos = BaseName.find(".cold"); if (ColdSuffixPos == StringRef::npos) continue; - // For cold function with local (foo.cold/1) symbol, prefer a parent with - // local symbol as well (foo/1) over global symbol (foo). - std::string ParentName = BaseName.substr(0, ColdSuffixPos).str(); + StringRef ParentName = BaseName.substr(0, ColdSuffixPos); const BinaryData *BD = BC->getBinaryDataByName(ParentName); - if (Suffix != "") { - ParentName.append(Twine("/", Suffix).str()); - const BinaryData *BDLocal = BC->getBinaryDataByName(ParentName); - if (BDLocal || !BD) - BD = BDLocal; - } - if (!BD) { - if (opts::Verbosity >= 1) - BC->outs() << "BOLT-INFO: parent function not found for " << Name - << "\n"; + const uint64_t NumPossibleLocalParents = + NR.getUniquifiedNameCount(ParentName); + // The most common case: single local parent fragment. + if (!BD && NumPossibleLocalParents == 1) { + BD = BC->getBinaryDataByName(NR.getUniqueName(ParentName, 1)); + } else if (BD && (!NumPossibleLocalParents || IsGlobal)) { + // Global parent and either no local candidates (second most common), or + // the fragment is global as well (uncommon). + } else { + // Any other case: need to disambiguate using FILE symbols. + AmbiguousFragments.emplace_back(ParentName, &Function); continue; } - const uint64_t Address = BD->getAddress(); - BinaryFunction *BF = BC->getBinaryFunctionAtAddress(Address); - if (!BF) { - if (opts::Verbosity >= 1) - BC->outs() << formatv( - "BOLT-INFO: parent function not found at {0:x}\n", Address); - continue; + if (BD) { + BinaryFunction *BF = BC->getFunctionForSymbol(BD->getSymbol()); + if (BF) { + BC->registerFragment(Function, *BF); + continue; + } } - BC->registerFragment(Function, *BF); - ++ParentsFound; - } - if (!ParentsFound) { BC->errs() << "BOLT-ERROR: parent function not found for " << Function << '\n'; exit(1); } } + + if (AmbiguousFragments.empty()) + return; + + if (!BC->hasSymbolsWithFileName()) { + BC->errs() << "BOLT-ERROR: input file has split functions but does not " + "have FILE symbols. If the binary was stripped, preserve " + "FILE symbols with --keep-file-symbols strip option"; + exit(1); + } + + // The first global symbol is identified by the symbol table sh_info value. + // Used as local symbol search stopping point. + auto *ELF64LEFile = cast(InputFile); + const ELFFile &Obj = ELF64LEFile->getELFFile(); + auto *SymTab = llvm::find_if(cantFail(Obj.sections()), [](const auto &Sec) { + return Sec.sh_type == ELF::SHT_SYMTAB; + }); + assert(SymTab); + // Symtab sh_info contains the value one greater than the symbol table index + // of the last local symbol. + ELFSymbolRef LocalSymEnd = ELF64LEFile->toSymbolRef(SymTab, SymTab->sh_info); + + for (auto &[ParentName, BF] : AmbiguousFragments) { + const uint64_t Address = BF->getAddress(); + + // Get fragment's own symbol + const auto SymIt = FileSymRefs.find(Address); + if (SymIt == FileSymRefs.end()) { + BC->errs() + << "BOLT-ERROR: symbol lookup failed for function at address 0x" + << Twine::utohexstr(Address) << '\n'; + exit(1); + } + + // Find containing FILE symbol + ELFSymbolRef Symbol = SymIt->second; + auto FSI = llvm::upper_bound(FileSymbols, Symbol); + if (FSI == FileSymbols.begin()) { + BC->errs() << "BOLT-ERROR: owning FILE symbol not found for symbol " + << cantFail(Symbol.getName()) << '\n'; + exit(1); + } + + ELFSymbolRef StopSymbol = LocalSymEnd; + if (FSI != FileSymbols.end()) + StopSymbol = *FSI; + + uint64_t ParentAddress{0}; + + // BOLT split fragment symbols are emitted just before the main function + // symbol. + for (ELFSymbolRef NextSymbol = Symbol; NextSymbol < StopSymbol; + NextSymbol.moveNext()) { + StringRef Name = cantFail(NextSymbol.getName()); + if (Name == ParentName) { + ParentAddress = cantFail(NextSymbol.getValue()); + goto registerParent; + } + if (Name.starts_with(ParentName)) + // With multi-way splitting, there are multiple fragments with different + // suffixes. Parent follows the last fragment. + continue; + break; + } + + // Iterate over local file symbols and check symbol names to match parent. + for (ELFSymbolRef Symbol(FSI[-1]); Symbol < StopSymbol; Symbol.moveNext()) { + if (cantFail(Symbol.getName()) == ParentName) { + ParentAddress = cantFail(Symbol.getAddress()); + break; + } + } + +registerParent: + // No local parent is found, use global parent function. + if (!ParentAddress) + if (BinaryData *ParentBD = BC->getBinaryDataByName(ParentName)) + ParentAddress = ParentBD->getAddress(); + + if (BinaryFunction *ParentBF = + BC->getBinaryFunctionAtAddress(ParentAddress)) { + BC->registerFragment(*BF, *ParentBF); + continue; + } + BC->errs() << "BOLT-ERROR: parent function not found for " << *BF << '\n'; + exit(1); + } } void RewriteInstance::createPLTBinaryFunction(uint64_t TargetAddress, @@ -3526,6 +3617,26 @@ void RewriteInstance::updateMetadata() { void RewriteInstance::mapFileSections(BOLTLinker::SectionMapper MapSection) { BC->deregisterUnusedSections(); + // Check if the input has a space reserved for BOLT. + BinaryData *StartBD = BC->getBinaryDataByName(getBOLTReservedStart()); + BinaryData *EndBD = BC->getBinaryDataByName(getBOLTReservedEnd()); + if (!StartBD != !EndBD) { + BC->errs() << "BOLT-ERROR: one of the symbols is missing from the binary: " + << getBOLTReservedStart() << ", " << getBOLTReservedEnd() + << '\n'; + exit(1); + } + + if (StartBD) { + PHDRTableOffset = 0; + PHDRTableAddress = 0; + NewTextSegmentAddress = 0; + NewTextSegmentOffset = 0; + NextAvailableAddress = StartBD->getAddress(); + BC->outs() + << "BOLT-INFO: using reserved space for allocating new sections\n"; + } + // If no new .eh_frame was written, remove relocated original .eh_frame. BinarySection *RelocatedEHFrameSection = getSection(".relocated" + getEHFrameSectionName()); @@ -3545,6 +3656,18 @@ void RewriteInstance::mapFileSections(BOLTLinker::SectionMapper MapSection) { // Map the rest of the sections. mapAllocatableSections(MapSection); + + if (StartBD) { + const uint64_t ReservedSpace = EndBD->getAddress() - StartBD->getAddress(); + const uint64_t AllocatedSize = NextAvailableAddress - StartBD->getAddress(); + if (ReservedSpace < AllocatedSize) { + BC->errs() << "BOLT-ERROR: reserved space (" << ReservedSpace << " byte" + << (ReservedSpace == 1 ? "" : "s") + << ") is smaller than required for new allocations (" + << AllocatedSize << " bytes)\n"; + exit(1); + } + } } std::vector RewriteInstance::getCodeSections() { @@ -3786,7 +3909,7 @@ void RewriteInstance::mapCodeSections(BOLTLinker::SectionMapper MapSection) { // Add the new text section aggregating all existing code sections. // This is pseudo-section that serves a purpose of creating a corresponding // entry in section header table. - int64_t NewTextSectionSize = + const uint64_t NewTextSectionSize = NextAvailableAddress - NewTextSectionStartAddress; if (NewTextSectionSize) { const unsigned Flags = BinarySection::getFlags(/*IsReadOnly=*/true, @@ -3869,7 +3992,7 @@ void RewriteInstance::mapAllocatableSections( if (PHDRTableAddress) { // Segment size includes the size of the PHDR area. NewTextSegmentSize = NextAvailableAddress - PHDRTableAddress; - } else { + } else if (NewTextSegmentAddress) { // Existing PHDR table would be updated. NewTextSegmentSize = NextAvailableAddress - NewTextSegmentAddress; } @@ -3908,7 +4031,7 @@ void RewriteInstance::patchELFPHDRTable() { assert(!PHDRTableAddress && "unexpected address for program header table"); PHDRTableOffset = Obj.getHeader().e_phoff; if (NewWritableSegmentSize) { - BC->errs() << "Unable to add writable segment with UseGnuStack option\n"; + BC->errs() << "BOLT-ERROR: unable to add writable segment\n"; exit(1); } } @@ -3918,19 +4041,15 @@ void RewriteInstance::patchELFPHDRTable() { if (!NewWritableSegmentSize) { if (PHDRTableAddress) NewTextSegmentSize = NextAvailableAddress - PHDRTableAddress; - else + else if (NewTextSegmentAddress) NewTextSegmentSize = NextAvailableAddress - NewTextSegmentAddress; } else { NewWritableSegmentSize = NextAvailableAddress - NewWritableSegmentAddress; } + const uint64_t SavedPos = OS.tell(); OS.seek(PHDRTableOffset); - bool ModdedGnuStack = false; - (void)ModdedGnuStack; - bool AddedSegment = false; - (void)AddedSegment; - auto createNewTextPhdr = [&]() { ELF64LEPhdrTy NewPhdr; NewPhdr.p_type = ELF::PT_LOAD; @@ -3946,40 +4065,55 @@ void RewriteInstance::patchELFPHDRTable() { NewPhdr.p_filesz = NewTextSegmentSize; NewPhdr.p_memsz = NewTextSegmentSize; NewPhdr.p_flags = ELF::PF_X | ELF::PF_R; - // FIXME: Currently instrumentation is experimental and the runtime data - // is emitted with code, thus everything needs to be writable - if (opts::Instrument) + if (opts::Instrument) { + // FIXME: Currently instrumentation is experimental and the runtime data + // is emitted with code, thus everything needs to be writable. NewPhdr.p_flags |= ELF::PF_W; + } NewPhdr.p_align = BC->PageAlign; return NewPhdr; }; - auto createNewWritableSectionsPhdr = [&]() { - ELF64LEPhdrTy NewPhdr; - NewPhdr.p_type = ELF::PT_LOAD; - NewPhdr.p_offset = getFileOffsetForAddress(NewWritableSegmentAddress); - NewPhdr.p_vaddr = NewWritableSegmentAddress; - NewPhdr.p_paddr = NewWritableSegmentAddress; - NewPhdr.p_filesz = NewWritableSegmentSize; - NewPhdr.p_memsz = NewWritableSegmentSize; - NewPhdr.p_align = BC->RegularPageSize; - NewPhdr.p_flags = ELF::PF_R | ELF::PF_W; - return NewPhdr; + auto writeNewSegmentPhdrs = [&]() { + if (PHDRTableAddress || NewTextSegmentSize) { + ELF64LE::Phdr NewPhdr = createNewTextPhdr(); + OS.write(reinterpret_cast(&NewPhdr), sizeof(NewPhdr)); + } + + if (NewWritableSegmentSize) { + ELF64LEPhdrTy NewPhdr; + NewPhdr.p_type = ELF::PT_LOAD; + NewPhdr.p_offset = getFileOffsetForAddress(NewWritableSegmentAddress); + NewPhdr.p_vaddr = NewWritableSegmentAddress; + NewPhdr.p_paddr = NewWritableSegmentAddress; + NewPhdr.p_filesz = NewWritableSegmentSize; + NewPhdr.p_memsz = NewWritableSegmentSize; + NewPhdr.p_align = BC->RegularPageSize; + NewPhdr.p_flags = ELF::PF_R | ELF::PF_W; + OS.write(reinterpret_cast(&NewPhdr), sizeof(NewPhdr)); + } }; + bool ModdedGnuStack = false; + bool AddedSegment = false; + // Copy existing program headers with modifications. for (const ELF64LE::Phdr &Phdr : cantFail(Obj.program_headers())) { ELF64LE::Phdr NewPhdr = Phdr; - if (PHDRTableAddress && Phdr.p_type == ELF::PT_PHDR) { - NewPhdr.p_offset = PHDRTableOffset; - NewPhdr.p_vaddr = PHDRTableAddress; - NewPhdr.p_paddr = PHDRTableAddress; - NewPhdr.p_filesz = sizeof(NewPhdr) * Phnum; - NewPhdr.p_memsz = sizeof(NewPhdr) * Phnum; - } else if (Phdr.p_type == ELF::PT_GNU_EH_FRAME) { - ErrorOr EHFrameHdrSec = - BC->getUniqueSectionByName(getNewSecPrefix() + ".eh_frame_hdr"); + switch (Phdr.p_type) { + case ELF::PT_PHDR: + if (PHDRTableAddress) { + NewPhdr.p_offset = PHDRTableOffset; + NewPhdr.p_vaddr = PHDRTableAddress; + NewPhdr.p_paddr = PHDRTableAddress; + NewPhdr.p_filesz = sizeof(NewPhdr) * Phnum; + NewPhdr.p_memsz = sizeof(NewPhdr) * Phnum; + } + break; + case ELF::PT_GNU_EH_FRAME: { + ErrorOr EHFrameHdrSec = BC->getUniqueSectionByName( + getNewSecPrefix() + getEHFrameHdrSectionName()); if (EHFrameHdrSec && EHFrameHdrSec->isAllocatable() && EHFrameHdrSec->isFinalized()) { NewPhdr.p_offset = EHFrameHdrSec->getOutputFileOffset(); @@ -3988,37 +4122,38 @@ void RewriteInstance::patchELFPHDRTable() { NewPhdr.p_filesz = EHFrameHdrSec->getOutputSize(); NewPhdr.p_memsz = EHFrameHdrSec->getOutputSize(); } - } else if (opts::UseGnuStack && Phdr.p_type == ELF::PT_GNU_STACK) { - NewPhdr = createNewTextPhdr(); - ModdedGnuStack = true; - } else if (!opts::UseGnuStack && Phdr.p_type == ELF::PT_DYNAMIC) { - // Insert the new header before DYNAMIC. - ELF64LE::Phdr NewTextPhdr = createNewTextPhdr(); - OS.write(reinterpret_cast(&NewTextPhdr), - sizeof(NewTextPhdr)); - if (NewWritableSegmentSize) { - ELF64LEPhdrTy NewWritablePhdr = createNewWritableSectionsPhdr(); - OS.write(reinterpret_cast(&NewWritablePhdr), - sizeof(NewWritablePhdr)); + break; + } + case ELF::PT_GNU_STACK: + if (opts::UseGnuStack) { + // Overwrite the header with the new text segment header. + NewPhdr = createNewTextPhdr(); + ModdedGnuStack = true; + } + break; + case ELF::PT_DYNAMIC: + if (!opts::UseGnuStack) { + // Insert new headers before DYNAMIC. + writeNewSegmentPhdrs(); + AddedSegment = true; } - AddedSegment = true; + break; } OS.write(reinterpret_cast(&NewPhdr), sizeof(NewPhdr)); } if (!opts::UseGnuStack && !AddedSegment) { - // Append the new header to the end of the table. - ELF64LE::Phdr NewTextPhdr = createNewTextPhdr(); - OS.write(reinterpret_cast(&NewTextPhdr), sizeof(NewTextPhdr)); - if (NewWritableSegmentSize) { - ELF64LEPhdrTy NewWritablePhdr = createNewWritableSectionsPhdr(); - OS.write(reinterpret_cast(&NewWritablePhdr), - sizeof(NewWritablePhdr)); - } + // Append new headers to the end of the table. + writeNewSegmentPhdrs(); + } + + if (opts::UseGnuStack && !ModdedGnuStack) { + BC->errs() + << "BOLT-ERROR: could not find PT_GNU_STACK program header to modify\n"; + exit(1); } - assert((!opts::UseGnuStack || ModdedGnuStack) && - "could not find GNU_STACK program header to modify"); + OS.seek(SavedPos); } namespace { @@ -4044,9 +4179,8 @@ void RewriteInstance::rewriteNoteSections() { const ELFFile &Obj = ELF64LEFile->getELFFile(); raw_fd_ostream &OS = Out->os(); - uint64_t NextAvailableOffset = getFileOffsetForAddress(NextAvailableAddress); - assert(NextAvailableOffset >= FirstNonAllocatableOffset && - "next available offset calculation failure"); + uint64_t NextAvailableOffset = std::max( + getFileOffsetForAddress(NextAvailableAddress), FirstNonAllocatableOffset); OS.seek(NextAvailableOffset); // Copy over non-allocatable section contents and update file offsets. @@ -4785,7 +4919,7 @@ void RewriteInstance::updateELFSymbolTable( ++NumHotDataSymsUpdated; } - if (*SymbolName == "_end") + if (*SymbolName == "_end" && NextAvailableAddress > Symbol.st_value) updateSymbolValue(*SymbolName, NextAvailableAddress); if (IsDynSym) @@ -4899,13 +5033,6 @@ void RewriteInstance::patchELFSymTabs(ELFObjectFile *File) { std::vector NewSectionIndex; getOutputSections(File, NewSectionIndex); - // Set pointer at the end of the output file, so we can pwrite old symbol - // tables if we need to. - uint64_t NextAvailableOffset = getFileOffsetForAddress(NextAvailableAddress); - assert(NextAvailableOffset >= FirstNonAllocatableOffset && - "next available offset calculation failure"); - Out->os().seek(NextAvailableOffset); - // Update dynamic symbol table. const ELFShdrTy *DynSymSection = nullptr; for (const ELFShdrTy &Section : cantFail(Obj.sections())) { @@ -5470,10 +5597,10 @@ void RewriteInstance::rewriteFile() { auto Streamer = BC->createStreamer(OS); // Make sure output stream has enough reserved space, otherwise // pwrite() will fail. - uint64_t Offset = OS.seek(getFileOffsetForAddress(NextAvailableAddress)); - (void)Offset; - assert(Offset == getFileOffsetForAddress(NextAvailableAddress) && - "error resizing output file"); + uint64_t Offset = std::max(getFileOffsetForAddress(NextAvailableAddress), + FirstNonAllocatableOffset); + Offset = OS.seek(Offset); + assert((Offset != (uint64_t)-1) && "Error resizing output file"); // Overwrite functions with fixed output address. This is mostly used by // non-relocation mode, with one exception: injected functions are covered @@ -5692,7 +5819,8 @@ void RewriteInstance::writeEHFrameHeader() { BC->AsmInfo->getCodePointerSize())); check_error(std::move(Er), "failed to parse EH frame"); - LLVM_DEBUG(dbgs() << "BOLT: writing a new .eh_frame_hdr\n"); + LLVM_DEBUG(dbgs() << "BOLT: writing a new " << getEHFrameHdrSectionName() + << '\n'); NextAvailableAddress = appendPadding(Out->os(), NextAvailableAddress, EHFrameHdrAlign); @@ -5704,25 +5832,35 @@ void RewriteInstance::writeEHFrameHeader() { std::vector NewEHFrameHdr = CFIRdWrt->generateEHFrameHeader( RelocatedEHFrame, NewEHFrame, EHFrameHdrOutputAddress, FailedAddresses); - assert(Out->os().tell() == EHFrameHdrFileOffset && "offset mismatch"); + Out->os().seek(EHFrameHdrFileOffset); Out->os().write(NewEHFrameHdr.data(), NewEHFrameHdr.size()); const unsigned Flags = BinarySection::getFlags(/*IsReadOnly=*/true, /*IsText=*/false, /*IsAllocatable=*/true); - BinarySection *OldEHFrameHdrSection = getSection(".eh_frame_hdr"); + BinarySection *OldEHFrameHdrSection = getSection(getEHFrameHdrSectionName()); if (OldEHFrameHdrSection) - OldEHFrameHdrSection->setOutputName(getOrgSecPrefix() + ".eh_frame_hdr"); + OldEHFrameHdrSection->setOutputName(getOrgSecPrefix() + + getEHFrameHdrSectionName()); BinarySection &EHFrameHdrSec = BC->registerOrUpdateSection( - getNewSecPrefix() + ".eh_frame_hdr", ELF::SHT_PROGBITS, Flags, nullptr, - NewEHFrameHdr.size(), /*Alignment=*/1); + getNewSecPrefix() + getEHFrameHdrSectionName(), ELF::SHT_PROGBITS, Flags, + nullptr, NewEHFrameHdr.size(), /*Alignment=*/1); EHFrameHdrSec.setOutputFileOffset(EHFrameHdrFileOffset); EHFrameHdrSec.setOutputAddress(EHFrameHdrOutputAddress); - EHFrameHdrSec.setOutputName(".eh_frame_hdr"); + EHFrameHdrSec.setOutputName(getEHFrameHdrSectionName()); NextAvailableAddress += EHFrameHdrSec.getOutputSize(); + if (const BinaryData *ReservedEnd = + BC->getBinaryDataByName(getBOLTReservedEnd())) { + if (NextAvailableAddress > ReservedEnd->getAddress()) { + BC->errs() << "BOLT-ERROR: unable to fit " << getEHFrameHdrSectionName() + << " into reserved space\n"; + exit(1); + } + } + // Merge new .eh_frame with the relocated original so that gdb can locate all // FDEs. if (RelocatedEHFrameSection) { diff --git a/bolt/test/X86/fragment-lite.s b/bolt/test/X86/fragment-lite.s index 97069bf8096e1ce56c88c28dd619e4ab1ff94bed..32d1f5a98b64a3732295d8f6898ce60b19e3c149 100644 --- a/bolt/test/X86/fragment-lite.s +++ b/bolt/test/X86/fragment-lite.s @@ -3,35 +3,42 @@ # RUN: split-file %s %t # RUN: llvm-mc -filetype=obj -triple x86_64-unknown-unknown %t/main.s -o %t.o # RUN: llvm-mc -filetype=obj -triple x86_64-unknown-unknown %t/baz.s -o %t.baz.o +# RUN: llvm-mc -filetype=obj -triple x86_64-unknown-unknown %t/baz2.s -o %t.baz2.o # RUN: link_fdata %s %t.o %t.main.fdata # RUN: link_fdata %s %t.baz.o %t.baz.fdata -# RUN: merge-fdata %t.main.fdata %t.baz.fdata > %t.fdata -# RUN: %clang %cflags %t.o %t.baz.o -o %t.exe -Wl,-q +# RUN: link_fdata %s %t.baz2.o %t.baz2.fdata +# RUN: merge-fdata %t.main.fdata %t.baz.fdata %t.baz2.fdata > %t.fdata +# RUN: %clang %cflags %t.o %t.baz.o %t.baz2.o -o %t.exe -Wl,-q # RUN: llvm-bolt %t.exe -o %t.out --lite=1 --data %t.fdata -v=1 -print-cfg \ # RUN: 2>&1 | FileCheck %s # CHECK: BOLT-INFO: processing main.cold.1 as a sibling of non-ignored function -# CHECK: BOLT-INFO: processing foo.cold.1/1 as a sibling of non-ignored function -# CHECK: BOLT-INFO: processing bar.cold.1/1 as a sibling of non-ignored function +# CHECK: BOLT-INFO: processing foo.cold.1/1(*2) as a sibling of non-ignored function +# CHECK: BOLT-INFO: processing bar.cold.1/1(*2) as a sibling of non-ignored function # CHECK: BOLT-INFO: processing baz.cold.1 as a sibling of non-ignored function -# CHECK: BOLT-INFO: processing baz.cold.1/1 as a sibling of non-ignored function +# CHECK: BOLT-INFO: processing baz.cold.1/1(*2) as a sibling of non-ignored function +# CHECK: BOLT-INFO: processing baz.cold.1/2(*2) as a sibling of non-ignored function # CHECK: Binary Function "main.cold.1" after building cfg # CHECK: Parent : main -# CHECK: Binary Function "foo.cold.1/1" after building cfg +# CHECK: Binary Function "foo.cold.1/1(*2)" after building cfg # CHECK: Parent : foo -# CHECK: Binary Function "bar.cold.1/1" after building cfg -# CHECK: Parent : bar/1 +# CHECK: Binary Function "bar.cold.1/1(*2)" after building cfg +# CHECK: Parent : bar/1(*2) # CHECK: Binary Function "baz.cold.1" after building cfg # CHECK: Parent : baz{{$}} -# CHECK: Binary Function "baz.cold.1/1" after building cfg -# CHECK: Parent : baz/1 +# CHECK: Binary Function "baz.cold.1/1(*2)" after building cfg +# CHECK: Parent : baz/1(*2) + +# CHECK: Binary Function "baz.cold.1/2(*2)" after building cfg +# CHECK: Parent : baz/2(*2) #--- main.s +.file "main.s" .globl main .type main, %function main: @@ -126,6 +133,7 @@ baz.cold.1: .size baz.cold.1, .-baz.cold.1 #--- baz.s +.file "baz.s" .local baz .type baz, %function baz: @@ -149,3 +157,29 @@ baz.cold.1: retq .cfi_endproc .size baz.cold.1, .-baz.cold.1 + +#--- baz2.s +.file "baz2.s" + .local baz + .type baz, %function +baz: + .cfi_startproc +# FDATA: 0 [unknown] 0 1 baz/2 0 1 0 + cmpl $0x0, %eax + je baz.cold.1 + retq + .cfi_endproc +.size baz, .-baz + + .section .text.cold + .local baz.cold.1 + .type baz.cold.1, %function +baz.cold.1: + .cfi_startproc + pushq %rbp + movq %rsp, %rbp + movl $0x0, %eax + popq %rbp + retq + .cfi_endproc +.size baz.cold.1, .-baz.cold.1 diff --git a/bolt/test/X86/register-fragments-bolt-symbols.s b/bolt/test/X86/register-fragments-bolt-symbols.s new file mode 100644 index 0000000000000000000000000000000000000000..fa9b70e0b2d8919a371b609263e03c1d902547bb --- /dev/null +++ b/bolt/test/X86/register-fragments-bolt-symbols.s @@ -0,0 +1,32 @@ +# Test the heuristics for matching BOLT-added split functions. + +# RUN: llvm-mc --filetype=obj --triple x86_64-unknown-unknown %S/cdsplit-symbol-names.s -o %t.main.o +# RUN: llvm-mc --filetype=obj --triple x86_64-unknown-unknown %s -o %t.chain.o +# RUN: link_fdata %S/cdsplit-symbol-names.s %t.main.o %t.fdata +# RUN: sed -i 's|chain|chain/2|g' %t.fdata +# RUN: llvm-strip --strip-unneeded %t.main.o +# RUN: llvm-objcopy --localize-symbol=chain %t.main.o +# RUN: %clang %cflags %t.chain.o %t.main.o -o %t.exe -Wl,-q +# RUN: llvm-bolt %t.exe -o %t.bolt --split-functions --split-strategy=randomN \ +# RUN: --reorder-blocks=ext-tsp --enable-bat --bolt-seed=7 --data=%t.fdata +# RUN: llvm-objdump --syms %t.bolt | FileCheck %s --check-prefix=CHECK-SYMS + +# RUN: link_fdata %s %t.bolt %t.preagg PREAGG +# PREAGG: B X:0 #chain.cold.0# 1 0 +# RUN: perf2bolt %t.bolt -p %t.preagg --pa -o %t.bat.fdata -w %t.bat.yaml -v=1 \ +# RUN: | FileCheck %s --check-prefix=CHECK-REGISTER + +# CHECK-SYMS: l df *ABS* [[#]] chain.s +# CHECK-SYMS: l F .bolt.org.text [[#]] chain +# CHECK-SYMS: l F .text.cold [[#]] chain.cold.0 +# CHECK-SYMS: l F .text [[#]] chain +# CHECK-SYMS: l df *ABS* [[#]] bolt-pseudo.o + +# CHECK-REGISTER: BOLT-INFO: marking chain.cold.0/1(*2) as a fragment of chain/2(*2) + +.file "chain.s" + .text + .type chain, @function +chain: + ret + .size chain, .-chain diff --git a/clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.h b/clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.h index 6c32a4edb4ff96ed48703067a7b52dc9041be4d7..f1591bae4465798750f1642eac64d70991d678cb 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.h +++ b/clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.h @@ -19,7 +19,7 @@ public: bool isLanguageVersionSupported(const LangOptions &LangOpts) const override { // FIXME this should be CPlusPlus11 but that causes test cases to // erroneously fail. - return LangOpts.CPlusPlus; + return LangOpts.CPlusPlus || LangOpts.C23; } void storeOptions(ClangTidyOptions::OptionMap &Opts) override; void registerMatchers(ast_matchers::MatchFinder *Finder) override; diff --git a/clang-tools-extra/clang-tidy/readability/AvoidReturnWithVoidValueCheck.cpp b/clang-tools-extra/clang-tidy/readability/AvoidReturnWithVoidValueCheck.cpp index 48bca41f4a3b1e87dbd7488617702f17e5f6e15a..f077040a35295e97c9f4606787757a6a04e0190e 100644 --- a/clang-tools-extra/clang-tidy/readability/AvoidReturnWithVoidValueCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/AvoidReturnWithVoidValueCheck.cpp @@ -64,8 +64,11 @@ void AvoidReturnWithVoidValueCheck::check( << BraceInsertionHints.closingBraceFixIt(); } Diag << FixItHint::CreateRemoval(VoidReturn->getReturnLoc()); - if (!Result.Nodes.getNodeAs("function_parent") || - SurroundingBlock->body_back() != VoidReturn) + const auto *FunctionParent = + Result.Nodes.getNodeAs("function_parent"); + if (!FunctionParent || + (SurroundingBlock && SurroundingBlock->body_back() != VoidReturn)) + // If this is not the last statement in a function body, we add a `return`. Diag << FixItHint::CreateInsertion(SemicolonPos.getLocWithOffset(1), " return;", true); } diff --git a/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp b/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp index d1e20b9074cec1b823aee92c927544c7a3ae6590..65fd296094915bbddf4e114e3ee96f8d5efb5f50 100644 --- a/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp @@ -61,19 +61,21 @@ static void addParantheses(const BinaryOperator *BinOp, const clang::SourceLocation StartLoc = BinOp->getBeginLoc(); const clang::SourceLocation EndLoc = clang::Lexer::getLocForEndOfToken(BinOp->getEndLoc(), 0, SM, LangOpts); - if (EndLoc.isInvalid()) - return; - Check->diag(StartLoc, - "'%0' has higher precedence than '%1'; add parentheses to " - "explicitly specify the order of operations") + auto Diag = + Check->diag(StartLoc, + "'%0' has higher precedence than '%1'; add parentheses to " + "explicitly specify the order of operations") << (Precedence1 > Precedence2 ? BinOp->getOpcodeStr() : ParentBinOp->getOpcodeStr()) << (Precedence1 > Precedence2 ? ParentBinOp->getOpcodeStr() : BinOp->getOpcodeStr()) - << FixItHint::CreateInsertion(StartLoc, "(") - << FixItHint::CreateInsertion(EndLoc, ")") << SourceRange(StartLoc, EndLoc); + + if (EndLoc.isValid()) { + Diag << FixItHint::CreateInsertion(StartLoc, "(") + << FixItHint::CreateInsertion(EndLoc, ")"); + } } addParantheses(dyn_cast(BinOp->getLHS()->IgnoreImpCasts()), diff --git a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp index 88aae2729904f4ae0859fe580cda0665b3104b45..94437857cecca6a94df8ad316b29b6302d812cd1 100644 --- a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp +++ b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp @@ -839,9 +839,7 @@ TEST_F(TargetDeclTest, OverloadExpr) { [[delete]] x; } )cpp"; - // Sized deallocation is enabled by default in C++14 onwards. - EXPECT_DECLS("CXXDeleteExpr", - "void operator delete(void *, unsigned long) noexcept"); + EXPECT_DECLS("CXXDeleteExpr", "void operator delete(void *) noexcept"); } TEST_F(TargetDeclTest, DependentExprs) { @@ -856,7 +854,7 @@ TEST_F(TargetDeclTest, DependentExprs) { } }; )cpp"; - EXPECT_DECLS("CXXDependentScopeMemberExpr", "void foo()"); + EXPECT_DECLS("MemberExpr", "void foo()"); // Similar to above but base expression involves a function call. Code = R"cpp( @@ -874,7 +872,7 @@ TEST_F(TargetDeclTest, DependentExprs) { } }; )cpp"; - EXPECT_DECLS("CXXDependentScopeMemberExpr", "void foo()"); + EXPECT_DECLS("MemberExpr", "void foo()"); // Similar to above but uses a function pointer. Code = R"cpp( @@ -893,7 +891,7 @@ TEST_F(TargetDeclTest, DependentExprs) { } }; )cpp"; - EXPECT_DECLS("CXXDependentScopeMemberExpr", "void foo()"); + EXPECT_DECLS("MemberExpr", "void foo()"); // Base expression involves a member access into this. Code = R"cpp( @@ -964,7 +962,7 @@ TEST_F(TargetDeclTest, DependentExprs) { void Foo() { this->[[find]](); } }; )cpp"; - EXPECT_DECLS("CXXDependentScopeMemberExpr", "void find()"); + EXPECT_DECLS("MemberExpr", "void find()"); } TEST_F(TargetDeclTest, DependentTypes) { diff --git a/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp b/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp index 4156921d83edf8e89484c9a5a449db7b8bc32e6c..30b9b1902aa9c72c6b97b1fab360302d1ccf725d 100644 --- a/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp +++ b/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp @@ -621,7 +621,7 @@ sizeof...($TemplateParameter[[Elements]]); struct $Class_def[[Foo]] { int $Field_decl[[Waldo]]; void $Method_def[[bar]]() { - $Class[[Foo]]().$Field_dependentName[[Waldo]]; + $Class[[Foo]]().$Field[[Waldo]]; } template $Bracket[[<]]typename $TemplateParameter_def[[U]]$Bracket[[>]] void $Method_def[[bar1]]() { diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 2867fc9580304816616648686aa45c5fae87a6ac..5956ccb925485c77c941029282d5dcac3fde9185 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -100,13 +100,15 @@ Improvements to clang-tidy - Improved :program:`run-clang-tidy.py` script. Added argument `-source-filter` to filter source files from the compilation database, via a RegEx. In a similar fashion to what `-header-filter` does for header files. + - Improved :program:`check_clang_tidy.py` script. Added argument `-export-fixes` to aid in clang-tidy and test development. + - Fixed bug where big values for unsigned check options overflowed into negative values - when being printed with ``--dump-config``. + when being printed with `--dump-config`. -- Fixed ``--verify-config`` option not properly parsing checks when using the - literal operator in the ``.clang-tidy`` config. +- Fixed `--verify-config` option not properly parsing checks when using the + literal operator in the `.clang-tidy` config. New checks ^^^^^^^^^^ @@ -236,7 +238,7 @@ Changes in existing checks - Improved :doc:`google-explicit-constructor ` check to better handle - ``C++-20`` `explicit(bool)`. + C++20 `explicit(bool)`. - Improved :doc:`google-global-names-in-headers ` check by replacing the local @@ -249,13 +251,18 @@ Changes in existing checks check by ignoring other functions with same prefixes as the target specific functions. +- Improved :doc:`linuxkernel-must-check-errs + ` check documentation to + consistently use the check's proper name. + - Improved :doc:`llvm-header-guard ` check by replacing the local option `HeaderFileExtensions` by the global option of the same name. - Improved :doc:`misc-const-correctness ` check by avoiding infinite recursion - for recursive forwarding reference. + for recursive functions with forwarding reference parameters and reference + variables which refer to themselves. - Improved :doc:`misc-definitions-in-headers ` check by replacing the local @@ -281,6 +288,10 @@ Changes in existing checks don't remove parentheses used in ``sizeof`` calls when they have array index accesses as arguments. +- Improved :doc:`modernize-use-nullptr + ` check to include support for C23, + which also has introduced the ``nullptr`` keyword. + - Improved :doc:`modernize-use-override ` check to also remove any trailing whitespace when deleting the ``virtual`` keyword. @@ -336,13 +347,9 @@ Miscellaneous ^^^^^^^^^^^^^ - Fixed incorrect formatting in :program:`clang-apply-replacements` when no - ``--format`` option is specified. Now :program:`clang-apply-replacements` + `--format` option is specified. Now :program:`clang-apply-replacements` applies formatting only with the option. -- Fixed the :doc:`linuxkernel-must-check-errs - ` documentation to consistently - use the check's proper name. - Improvements to include-fixer ----------------------------- diff --git a/clang-tools-extra/docs/clang-tidy/checks/modernize/use-nullptr.rst b/clang-tools-extra/docs/clang-tidy/checks/modernize/use-nullptr.rst index 5e1ba858adf3a9c42e20f8334781cd8dc6c2aab7..25e17fee0a3d6106cc83e86297ea8541990802c0 100644 --- a/clang-tools-extra/docs/clang-tidy/checks/modernize/use-nullptr.rst +++ b/clang-tools-extra/docs/clang-tidy/checks/modernize/use-nullptr.rst @@ -4,7 +4,7 @@ modernize-use-nullptr ===================== The check converts the usage of null pointer constants (e.g. ``NULL``, ``0``) -to use the new C++11 ``nullptr`` keyword. +to use the new C++11 and C23 ``nullptr`` keyword. Example ------- diff --git a/clang-tools-extra/test/CMakeLists.txt b/clang-tools-extra/test/CMakeLists.txt index f4c529ee8af2077f715568f3e84f524932c457c3..7a1c168e22f97c6796f10e8c24ed1ae69f78c732 100644 --- a/clang-tools-extra/test/CMakeLists.txt +++ b/clang-tools-extra/test/CMakeLists.txt @@ -67,33 +67,30 @@ foreach(dep ${LLVM_UTILS_DEPS}) endif() endforeach() -if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY) - if (NOT WIN32 OR NOT LLVM_LINK_LLVM_DYLIB) - llvm_add_library( - CTTestTidyModule - MODULE clang-tidy/CTTestTidyModule.cpp - PLUGIN_TOOL clang-tidy - DEPENDS clang-tidy-headers) - endif() +if (NOT WIN32 OR NOT LLVM_LINK_LLVM_DYLIB) + llvm_add_library( + CTTestTidyModule + MODULE clang-tidy/CTTestTidyModule.cpp + PLUGIN_TOOL clang-tidy) +endif() - if(CLANG_BUILT_STANDALONE) - # LLVMHello library is needed below - if (EXISTS ${LLVM_MAIN_SRC_DIR}/lib/Transforms/Hello - AND NOT TARGET LLVMHello) - add_subdirectory(${LLVM_MAIN_SRC_DIR}/lib/Transforms/Hello - lib/Transforms/Hello) - endif() +if(CLANG_BUILT_STANDALONE) + # LLVMHello library is needed below + if (EXISTS ${LLVM_MAIN_SRC_DIR}/lib/Transforms/Hello + AND NOT TARGET LLVMHello) + add_subdirectory(${LLVM_MAIN_SRC_DIR}/lib/Transforms/Hello + lib/Transforms/Hello) endif() +endif() - if(TARGET CTTestTidyModule) - list(APPEND CLANG_TOOLS_TEST_DEPS CTTestTidyModule LLVMHello) - target_include_directories(CTTestTidyModule PUBLIC BEFORE "${CLANG_TOOLS_SOURCE_DIR}") - if(CLANG_PLUGIN_SUPPORT AND (WIN32 OR CYGWIN)) - set(LLVM_LINK_COMPONENTS - Support - ) - endif() - endif() +if(TARGET CTTestTidyModule) + list(APPEND CLANG_TOOLS_TEST_DEPS CTTestTidyModule LLVMHello) + target_include_directories(CTTestTidyModule PUBLIC BEFORE "${CLANG_TOOLS_SOURCE_DIR}") + if(CLANG_PLUGIN_SUPPORT AND (WIN32 OR CYGWIN)) + set(LLVM_LINK_COMPONENTS + Support + ) + endif() endif() add_lit_testsuite(check-clang-extra "Running clang-tools-extra/test" diff --git a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/owning-memory.cpp b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/owning-memory.cpp index 574efe7bd91478de9c25ab92570c28eb292e0ef2..ae61b17ca14d206bc91342490d2df2e124506ffd 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/owning-memory.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/owning-memory.cpp @@ -309,6 +309,8 @@ struct HeapArray { // Ok, since destruc HeapArray(HeapArray &&other) : _data(other._data), size(other.size) { // Ok other._data = nullptr; // Ok + // CHECK-NOTES: [[@LINE-1]]:5: warning: expected assignment source to be of type 'gsl::owner<>'; got 'std::nullptr_t' + // FIXME: This warning is emitted because an ImplicitCastExpr for the NullToPointer conversion isn't created for dependent types. other.size = 0; } diff --git a/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp b/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp index f86fe8a4c5b14f606bd5a37c6c8b283682223a11..78f021144b2e19c1d8f91534cf0c6b0242e8dec7 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp @@ -12,6 +12,16 @@ struct S { // CHECK-MESSAGES: :[[@LINE+1]]:7: warning: declaration of 'operator new' has no matching declaration of 'operator delete' at the same scope void *operator new(size_t size) noexcept(false); +struct T { + // Sized deallocations are not enabled by default, and so this new/delete pair + // does not match. However, we expect only one warning, for the new, because + // the operator delete is a placement delete and we do not warn on mismatching + // placement operations. + // CHECK-MESSAGES: :[[@LINE+1]]:9: warning: declaration of 'operator new' has no matching declaration of 'operator delete' at the same scope + void *operator new(size_t size) noexcept; + void operator delete(void *ptr, size_t) noexcept; // ok only if sized deallocation is enabled +}; + struct U { void *operator new(size_t size) noexcept; void operator delete(void *ptr) noexcept; diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp index 559031cf4d9bda8ca15b547d19bd83d90af8e0da..4abb9c8555970ebdb76339df945512867c424bca 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp @@ -260,6 +260,8 @@ template struct Template { Template() = default; Template(const Template &Other) : Field(Other.Field) {} + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use '= default' + // CHECK-FIXES: Template(const Template &Other) = default; Template &operator=(const Template &Other); void foo(const T &t); int Field; @@ -269,8 +271,12 @@ Template &Template::operator=(const Template &Other) { Field = Other.Field; return *this; } +// CHECK-MESSAGES: :[[@LINE-4]]:27: warning: use '= default' +// CHECK-FIXES: Template &Template::operator=(const Template &Other) = default; + Template T1; + // Dependent types. template struct DT1 { @@ -284,6 +290,9 @@ DT1 &DT1::operator=(const DT1 &Other) { Field = Other.Field; return *this; } +// CHECK-MESSAGES: :[[@LINE-4]]:17: warning: use '= default' +// CHECK-FIXES: DT1 &DT1::operator=(const DT1 &Other) = default; + DT1 Dt1; template @@ -303,6 +312,9 @@ DT2 &DT2::operator=(const DT2 &Other) { struct T { typedef int TT; }; +// CHECK-MESSAGES: :[[@LINE-8]]:17: warning: use '= default' +// CHECK-FIXES: DT2 &DT2::operator=(const DT2 &Other) = default; + DT2 Dt2; // Default arguments. diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-nullptr-c23.c b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-nullptr-c23.c new file mode 100644 index 0000000000000000000000000000000000000000..6fb879b91e41c1c5ee0ab97bc76bd8ce072cc2c1 --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-nullptr-c23.c @@ -0,0 +1,139 @@ +// RUN: %check_clang_tidy %s modernize-use-nullptr %t -- -- -std=c23 + +#define NULL 0 + +void test_assignment() { + int *p1 = 0; + // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use nullptr [modernize-use-nullptr] + // CHECK-FIXES: int *p1 = nullptr; + p1 = 0; + // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: use nullptr + // CHECK-FIXES: p1 = nullptr; + + int *p2 = NULL; + // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use nullptr + // CHECK-FIXES: int *p2 = nullptr; + + p2 = p1; + // CHECK-FIXES: p2 = p1; + + const int null = 0; + int *p3 = &null; + + p3 = NULL; + // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: use nullptr + // CHECK-FIXES: p3 = nullptr; + + int *p4 = p3; + + int i1 = 0; + + int i2 = NULL; + + int i3 = null; + + int *p5, *p6, *p7; + p5 = p6 = p7 = NULL; + // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: use nullptr + // CHECK-FIXES: p5 = p6 = p7 = nullptr; +} + +void test_function(int *p) {} + +void test_function_no_ptr_param(int i) {} + +void test_function_call() { + test_function(0); + // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: use nullptr + // CHECK-FIXES: test_function(nullptr); + + test_function(NULL); + // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: use nullptr + // CHECK-FIXES: test_function(nullptr); + + test_function_no_ptr_param(0); +} + +char *test_function_return1() { + return 0; + // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: use nullptr + // CHECK-FIXES: return nullptr; +} + +void *test_function_return2() { + return NULL; + // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: use nullptr + // CHECK-FIXES: return nullptr; +} + +int test_function_return4() { + return 0; +} + +int test_function_return5() { + return NULL; +} + +int *test_function_return_cast1() { + return(int)0; + // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: use nullptr + // CHECK-FIXES: return nullptr; +} + +int *test_function_return_cast2() { +#define RET return + RET(int)0; + // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use nullptr + // CHECK-FIXES: RET nullptr; +#undef RET +} + +// Test parentheses expressions resulting in a nullptr. +int *test_parentheses_expression1() { + return(0); + // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: use nullptr + // CHECK-FIXES: return(nullptr); +} + +int *test_parentheses_expression2() { + return((int)(0.0f)); + // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: use nullptr + // CHECK-FIXES: return(nullptr); +} + +int *test_nested_parentheses_expression() { + return((((0)))); + // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use nullptr + // CHECK-FIXES: return((((nullptr)))); +} + +void test_const_pointers() { + const int *const_p1 = 0; + // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: use nullptr + // CHECK-FIXES: const int *const_p1 = nullptr; + const int *const_p2 = NULL; + // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: use nullptr + // CHECK-FIXES: const int *const_p2 = nullptr; + const int *const_p3 = (int)0; + // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: use nullptr + // CHECK-FIXES: const int *const_p3 = nullptr; + const int *const_p4 = (int)0.0f; + // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: use nullptr + // CHECK-FIXES: const int *const_p4 = nullptr; +} + +void test_nested_implicit_cast_expr() { + int func0(void*, void*); + int func1(int, void*, void*); + + (double)func1(0, 0, 0); + // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: use nullptr + // CHECK-MESSAGES: :[[@LINE-2]]:23: warning: use nullptr + // CHECK-FIXES: (double)func1(0, nullptr, nullptr); + (double)func1(func0(0, 0), 0, 0); + // CHECK-MESSAGES: :[[@LINE-1]]:23: warning: use nullptr + // CHECK-MESSAGES: :[[@LINE-2]]:26: warning: use nullptr + // CHECK-MESSAGES: :[[@LINE-3]]:30: warning: use nullptr + // CHECK-MESSAGES: :[[@LINE-4]]:33: warning: use nullptr + // CHECK-FIXES: (double)func1(func0(nullptr, nullptr), nullptr, nullptr); +} diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-nullptr.c b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-nullptr.c index c2ccbbd81171526ba6447ca244cb85a98b3868ab..1218b837199c0c2dcc3f857ac63d7f83366141e2 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-nullptr.c +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-nullptr.c @@ -1,4 +1,4 @@ -// RUN: clang-tidy %s -checks=-*,modernize-use-nullptr -- | count 0 +// RUN: clang-tidy %s -checks=-*,modernize-use-nullptr -- -std=c17 | count 0 // Note: this test expects no diagnostics, but FileCheck cannot handle that, // hence the use of | count 0. diff --git a/clang-tools-extra/test/clang-tidy/checkers/readability/math-missing-parentheses.cpp b/clang-tools-extra/test/clang-tidy/checkers/readability/math-missing-parentheses.cpp index edbe2e1c37c770c013423593675a89f301794c46..a6045c079a4823bb0852e64e15a0d8853bd13bc7 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/readability/math-missing-parentheses.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/readability/math-missing-parentheses.cpp @@ -16,6 +16,13 @@ int bar(){ return 4; } +int sink(int); +#define FUN(ARG) (sink(ARG)) +#define FUN2(ARG) sink((ARG)) +#define FUN3(ARG) sink(ARG) +#define FUN4(ARG) sink(1 + ARG) +#define FUN5(ARG) sink(4 * ARG) + class fun{ public: int A; @@ -117,4 +124,19 @@ void f(){ //CHECK-MESSAGES: :[[@LINE+2]]:94: warning: '/' has higher precedence than '-'; add parentheses to explicitly specify the order of operations [readability-math-missing-parentheses] //CHECK-FIXES: int q = (1 MACRO_ADD (2 MACRO_MULTIPLY 3)) MACRO_OR ((4 MACRO_AND 5) MACRO_XOR (6 MACRO_SUBTRACT (7 MACRO_DIVIDE 8))); int q = 1 MACRO_ADD 2 MACRO_MULTIPLY 3 MACRO_OR 4 MACRO_AND 5 MACRO_XOR 6 MACRO_SUBTRACT 7 MACRO_DIVIDE 8; // No warning + + //CHECK-MESSAGES: :[[@LINE+1]]:21: warning: '*' has higher precedence than '+'; add parentheses to explicitly specify the order of operations [readability-math-missing-parentheses] + int r = FUN(0 + 1 * 2); + + //CHECK-MESSAGES: :[[@LINE+1]]:22: warning: '*' has higher precedence than '+'; add parentheses to explicitly specify the order of operations [readability-math-missing-parentheses] + int s = FUN2(0 + 1 * 2); + + //CHECK-MESSAGES: :[[@LINE+1]]:22: warning: '*' has higher precedence than '+'; add parentheses to explicitly specify the order of operations [readability-math-missing-parentheses] + int t = FUN3(0 + 1 * 2); + + //CHECK-MESSAGES: :[[@LINE+1]]:18: warning: '*' has higher precedence than '+'; add parentheses to explicitly specify the order of operations [readability-math-missing-parentheses] + int u = FUN4(1 * 2); + + //CHECK-MESSAGES: :[[@LINE+1]]:13: warning: '*' has higher precedence than '+'; add parentheses to explicitly specify the order of operations [readability-math-missing-parentheses] + int v = FUN5(0 + 1); } diff --git a/clang-tools-extra/test/lit.site.cfg.py.in b/clang-tools-extra/test/lit.site.cfg.py.in index 4eb830a1baf1f1580e80d5dbec0581ae1a0aa980..e6503a4c097cac5520ab7a06a8e5aefa23bc88fa 100644 --- a/clang-tools-extra/test/lit.site.cfg.py.in +++ b/clang-tools-extra/test/lit.site.cfg.py.in @@ -10,7 +10,7 @@ config.python_executable = "@Python3_EXECUTABLE@" config.target_triple = "@LLVM_TARGET_TRIPLE@" config.host_triple = "@LLVM_HOST_TRIPLE@" config.clang_tidy_staticanalyzer = @CLANG_TIDY_ENABLE_STATIC_ANALYZER@ -config.has_plugins = @CLANG_PLUGIN_SUPPORT@ & ~@LLVM_INSTALL_TOOLCHAIN_ONLY@ +config.has_plugins = @CLANG_PLUGIN_SUPPORT@ # Support substitution of the tools and libs dirs with user parameters. This is # used when we can't determine the tool dir at configuration time. config.llvm_tools_dir = lit_config.substitute("@LLVM_TOOLS_DIR@") diff --git a/clang/cmake/caches/Release.cmake b/clang/cmake/caches/Release.cmake index c164d5497275f39aad374dff0aa55bdcbc3dc2cf..c0bfcbdfc1c2ae6cb32edfcb26e376baa1dd2641 100644 --- a/clang/cmake/caches/Release.cmake +++ b/clang/cmake/caches/Release.cmake @@ -82,6 +82,7 @@ set(LLVM_ENABLE_PROJECTS ${STAGE1_PROJECTS} CACHE STRING "") # stage2-instrumented and Final Stage Config: # Options that need to be set in both the instrumented stage (if we are doing # a pgo build) and the final stage. +set_instrument_and_final_stage_var(CMAKE_POSITION_INDEPENDENT_CODE "ON" STRING) set_instrument_and_final_stage_var(LLVM_ENABLE_LTO "${LLVM_RELEASE_ENABLE_LTO}" STRING) if (LLVM_RELEASE_ENABLE_LTO) set_instrument_and_final_stage_var(LLVM_ENABLE_LLD "ON" BOOL) diff --git a/clang/docs/LanguageExtensions.rst b/clang/docs/LanguageExtensions.rst index f18b946efd4bfa1df6cd9095104cef23c2d147a4..c2e90f4e7d587ada3c26a321def23227b56ed95f 100644 --- a/clang/docs/LanguageExtensions.rst +++ b/clang/docs/LanguageExtensions.rst @@ -711,6 +711,8 @@ even-odd element pair with indices ``i * 2`` and ``i * 2 + 1`` with power of 2, the vector is widened with neutral elements for the reduction at the end to the next power of 2. +These reductions support both fixed-sized and scalable vector types. + Example: .. code-block:: c++ @@ -1493,6 +1495,7 @@ Conditional ``explicit`` __cpp_conditional_explicit C+ ``if consteval`` __cpp_if_consteval C++23 C++20 ``static operator()`` __cpp_static_call_operator C++23 C++03 Attributes on Lambda-Expressions C++23 C++11 +Attributes on Structured Bindings __cpp_structured_bindings C++26 C++03 ``= delete ("should have a reason");`` __cpp_deleted_function C++26 C++03 -------------------------------------------- -------------------------------- ------------- ------------- Designated initializers (N494) C99 C89 @@ -2928,7 +2931,7 @@ Query for this feature with ``__has_builtin(__builtin_dump_struct)`` ``__builtin_shufflevector`` is used to express generic vector permutation/shuffle/swizzle operations. This builtin is also very important for the implementation of various target-specific header files like -````. +````. This builtin can be used within constant expressions. **Syntax**: @@ -2955,7 +2958,7 @@ for the implementation of various target-specific header files like // Concatenate every other element of 8-element vectors V1 and V2. __builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14) - // Shuffle v1 with some elements being undefined + // Shuffle v1 with some elements being undefined. Not allowed in constexpr. __builtin_shufflevector(v1, v1, 3, -1, 1, -1) **Description**: @@ -2968,6 +2971,7 @@ starting with the first vector, continuing into the second vector. Thus, if ``vec1`` is a 4-element vector, index 5 would refer to the second element of ``vec2``. An index of -1 can be used to indicate that the corresponding element in the returned vector is a don't care and can be optimized by the backend. +Values of -1 are not supported in constant expressions. The result of ``__builtin_shufflevector`` is a vector with the same element type as ``vec1``/``vec2`` but that has an element count equal to the number of @@ -2982,7 +2986,8 @@ Query for this feature with ``__has_builtin(__builtin_shufflevector)``. ``__builtin_convertvector`` is used to express generic vector type-conversion operations. The input vector and the output vector -type must have the same number of elements. +type must have the same number of elements. This builtin can be used within +constant expressions. **Syntax**: diff --git a/clang/docs/LibTooling.rst b/clang/docs/LibTooling.rst index df50dcebf9b83c72704aa9a7ba4b2c2578336a8d..87d84321ab2830837dbba25a6d8746f35a3b01d0 100644 --- a/clang/docs/LibTooling.rst +++ b/clang/docs/LibTooling.rst @@ -63,15 +63,22 @@ and automatic location of the compilation database using source files paths. #include "llvm/Support/CommandLine.h" using namespace clang::tooling; + using namespace llvm; // Apply a custom category to all command-line options so that they are the // only ones displayed. - static llvm::cl::OptionCategory MyToolCategory("my-tool options"); + static cl::OptionCategory MyToolCategory("my-tool options"); int main(int argc, const char **argv) { - // CommonOptionsParser constructor will parse arguments and create a - // CompilationDatabase. In case of error it will terminate the program. - CommonOptionsParser OptionsParser(argc, argv, MyToolCategory); + // CommonOptionsParser::create will parse arguments and create a + // CompilationDatabase. + auto ExpectedParser = CommonOptionsParser::create(argc, argv, MyToolCategory); + if (!ExpectedParser) { + // Fail gracefully for unsupported options. + llvm::errs() << ExpectedParser.takeError(); + return 1; + } + CommonOptionsParser& OptionsParser = ExpectedParser.get(); // Use OptionsParser.getCompilations() and OptionsParser.getSourcePathList() // to retrieve CompilationDatabase and the list of input file paths. @@ -133,7 +140,12 @@ version of this example tool is also checked into the clang tree at static cl::extrahelp MoreHelp("\nMore help text...\n"); int main(int argc, const char **argv) { - CommonOptionsParser OptionsParser(argc, argv, MyToolCategory); + auto ExpectedParser = CommonOptionsParser::create(argc, argv, MyToolCategory); + if (!ExpectedParser) { + llvm::errs() << ExpectedParser.takeError(); + return 1; + } + CommonOptionsParser& OptionsParser = ExpectedParser.get(); ClangTool Tool(OptionsParser.getCompilations(), OptionsParser.getSourcePathList()); return Tool.run(newFrontendActionFactory().get()); diff --git a/clang/docs/Multilib.rst b/clang/docs/Multilib.rst index ab737e43b97d230a0a827dc92d7b30f5674b1b07..063fe9a336f2fe92e785eb27e7f4f47ec5f15f34 100644 --- a/clang/docs/Multilib.rst +++ b/clang/docs/Multilib.rst @@ -188,9 +188,9 @@ For a more comprehensive example see - Dir: thumb/v6-m # List of one or more normalized command line options, as generated by Clang # from the command line options or from Mappings below. - # Here, if the flags are a superset of {target=thumbv6m-none-unknown-eabi} + # Here, if the flags are a superset of {target=thumbv6m-unknown-none-eabi} # then this multilib variant will be considered a match. - Flags: [--target=thumbv6m-none-unknown-eabi] + Flags: [--target=thumbv6m-unknown-none-eabi] # Similarly, a multilib variant targeting Arm v7-M with an FPU (floating # point unit). diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 5d4d152b2eb5408a178619790487a8d3a2a017a5..0e3f7cf89ca88517c78e4d0cb32b3198d3d7d9e8 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -63,6 +63,12 @@ ABI Changes in This Version MSVC uses a different mangling for these objects, compatibility is not affected. (#GH85423). +- Fixed Microsoft calling convention for returning certain classes with a + templated constructor. If a class has a templated constructor, it should + be returned indirectly even if it meets all the other requirements for + returning a class in a register. This affects some uses of std::pair. + (#GH86384). + AST Dumping Potentially Breaking Changes ---------------------------------------- @@ -90,11 +96,6 @@ C++ Language Changes -------------------- - Implemented ``_BitInt`` literal suffixes ``__wb`` or ``__WB`` as a Clang extension with ``unsigned`` modifiers also allowed. (#GH85223). -C++14 Feature Support -^^^^^^^^^^^^^^^^^^^^^ -- Sized deallocation is enabled by default in C++14 onwards. The user may specify - ``-fno-sized-deallocation`` to disable it if there are some regressions. - C++17 Feature Support ^^^^^^^^^^^^^^^^^^^^^ - Clang now exposes ``__GCC_DESTRUCTIVE_SIZE`` and ``__GCC_CONSTRUCTIVE_SIZE`` @@ -148,6 +149,9 @@ C++2c Feature Support - Implemented `P2573R2: = delete("should have a reason"); `_ +- Implemented `P0609R3: Attributes for Structured Bindings `_ + +- Implemented `P2748R5 Disallow Binding a Returned Glvalue to a Temporary `_. Resolutions to C++ Defect Reports ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -224,6 +228,7 @@ Non-comprehensive list of changes in this release - ``__typeof_unqual__`` is available in all C modes as an extension, which behaves like ``typeof_unqual`` from C23, similar to ``__typeof__`` and ``typeof``. +- ``__builtin_reduce_{add|mul|xor|or|and|min|max}`` builtins now support scalable vectors. * Shared libraries linked with either the ``-ffast-math``, ``-Ofast``, or ``-funsafe-math-optimizations`` flags will no longer enable flush-to-zero @@ -234,6 +239,9 @@ Non-comprehensive list of changes in this release * ``-fdenormal-fp-math=preserve-sign`` is no longer implied by ``-ffast-math`` on x86 systems. +- Builtins ``__builtin_shufflevector()`` and ``__builtin_convertvector()`` may + now be used within constant expressions. + New Compiler Flags ------------------ - ``-fsanitize=implicit-bitfield-conversion`` checks implicit truncation and @@ -248,6 +256,10 @@ New Compiler Flags - ``-fexperimental-modules-reduced-bmi`` enables the Reduced BMI for C++20 named modules. See the document of standard C++ modules for details. +- ``-fexperimental-late-parse-attributes`` enables an experimental feature to + allow late parsing certain attributes in specific contexts where they would + not normally be late parsed. + Deprecated Compiler Flags ------------------------- @@ -402,6 +414,18 @@ Improvements to Clang's diagnostics - Clang now diagnoses requires expressions with explicit object parameters. +- Clang now looks up members of the current instantiation in the template definition context + if the current instantiation has no dependent base classes. + + .. code-block:: c++ + + template + struct A { + int f() { + return this->x; // error: no member named 'x' in 'A' + } + }; + Improvements to Clang's time-trace ---------------------------------- @@ -448,6 +472,9 @@ Bug Fixes in This Version - Clang now correctly generates overloads for bit-precise integer types for builtin operators in C++. Fixes #GH82998. +- Fix crash when destructor definition is preceded with an equals sign. + Fixes (#GH89544). + - When performing mixed arithmetic between ``_Complex`` floating-point types and integers, Clang now correctly promotes the integer to its corresponding real floating-point type only rather than to the complex type (e.g. ``_Complex float / int`` is now evaluated @@ -463,6 +490,10 @@ Bug Fixes in This Version - Fixed an assertion failure on invalid InitListExpr in C89 mode (#GH88008). +- Fixed missing destructor calls when we branch from middle of an expression. + This could happen through a branch in stmt-expr or in an expression containing a coroutine + suspension. Fixes (#GH63818) (#GH88478). + - Clang will no longer diagnose an erroneous non-dependent ``switch`` condition during instantiation, and instead will only diagnose it once, during checking of the function template. @@ -593,6 +624,12 @@ Bug Fixes to C++ Support - Fixed a use-after-free bug in parsing of type constraints with default arguments that involve lambdas. (#GH67235) - Fixed bug in which the body of a consteval lambda within a template was not parsed as within an immediate function context. +- Fix CTAD for ``std::initializer_list``. This allows ``std::initializer_list{1, 2, 3}`` to be deduced as + ``std::initializer_list`` as intended. +- Fix a bug on template partial specialization whose template parameter is `decltype(auto)`. +- Fix a bug on template partial specialization with issue on deduction of nontype template parameter + whose type is `decltype(auto)`. Fixes (#GH68885). +- Clang now correctly treats the noexcept-specifier of a friend function to be a complete-class context. Bug Fixes to AST Handling ^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -645,6 +682,7 @@ Arm and AArch64 Support * Arm Cortex-A78AE (cortex-a78ae). * Arm Cortex-A520AE (cortex-a520ae). * Arm Cortex-A720AE (cortex-a720ae). + * Arm Cortex-R82AE (cortex-r82ae). * Arm Neoverse-N3 (neoverse-n3). * Arm Neoverse-V3 (neoverse-v3). * Arm Neoverse-V3AE (neoverse-v3ae). @@ -704,6 +742,11 @@ AIX Support WebAssembly Support ^^^^^^^^^^^^^^^^^^^ +The -mcpu=generic configuration now enables multivalue feature, which is +standardized and available in all major engines. Enabling multivalue here only +enables the language feature but does not turn on the multivalue ABI (this +enables non-ABI uses of multivalue, like exnref). + AVR Support ^^^^^^^^^^^ diff --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst index d0326f01d251e02ea2e44ef671d5b548ff034768..370de7d9c769e8173b7dc3ddcc6f70d9e12ef115 100644 --- a/clang/docs/UsersManual.rst +++ b/clang/docs/UsersManual.rst @@ -1452,8 +1452,6 @@ floating point semantic models: precise (the default), strict, and fast. "fenv_access", "off", "on", "off" "rounding_mode", "tonearest", "dynamic", "tonearest" "contract", "on", "off", "fast" - "denormal_fp_math", "IEEE", "IEEE", "IEEE" - "denormal_fp32_math", "IEEE","IEEE", "IEEE" "support_math_errno", "on", "on", "off" "no_honor_nans", "off", "off", "on" "no_honor_infinities", "off", "off", "on" @@ -1462,6 +1460,14 @@ floating point semantic models: precise (the default), strict, and fast. "allow_approximate_fns", "off", "off", "on" "allow_reassociation", "off", "off", "on" +The ``-ffp-model`` option does not modify the ``fdenormal-fp-math`` +setting, but it does have an impact on whether ``crtfastmath.o`` is +linked. Because linking ``crtfastmath.o`` has a global effect on the +program, and because the global denormal handling can be changed in +other ways, the state of ``fdenormal-fp-math`` handling cannot +be assumed in any function based on fp-model. See :ref:`crtfastmath.o` +for more details. + .. option:: -ffast-math Enable fast-math mode. This option lets the @@ -1537,7 +1543,6 @@ floating point semantic models: precise (the default), strict, and fast. Also, this option resets following options to their target-dependent defaults. * ``-f[no-]math-errno`` - * ``-fdenormal-fp-math=`` There is ambiguity about how ``-ffp-contract``, ``-ffast-math``, and ``-fno-fast-math`` behave when combined. To keep the value of @@ -1560,8 +1565,7 @@ floating point semantic models: precise (the default), strict, and fast. ``-ffp-contract`` setting is determined by the default value of ``-ffp-contract``. - Note: ``-fno-fast-math`` implies ``-fdenormal-fp-math=ieee``. - ``-fno-fast-math`` causes ``crtfastmath.o`` to not be linked with code + Note: ``-fno-fast-math`` causes ``crtfastmath.o`` to not be linked with code unless ``-mdaz-ftz`` is present. .. option:: -fdenormal-fp-math= @@ -1692,9 +1696,7 @@ floating point semantic models: precise (the default), strict, and fast. * ``-fno-associative-math`` * ``-fno-reciprocal-math`` * ``-fsigned-zeros`` - * ``-ftrapping-math`` * ``-ffp-contract=on`` - * ``-fdenormal-fp-math=ieee`` There is ambiguity about how ``-ffp-contract``, ``-funsafe-math-optimizations``, and ``-fno-unsafe-math-optimizations`` @@ -2319,6 +2321,8 @@ are listed below. on ELF targets when using the integrated assembler. This flag currently only has an effect on ELF targets. +.. _funique_internal_linkage_names: + .. option:: -f[no]-unique-internal-linkage-names Controls whether Clang emits a unique (best-effort) symbol name for internal @@ -2448,27 +2452,41 @@ usual build cycle when using sample profilers for optimization: usual build flags that you always build your application with. The only requirement is that DWARF debug info including source line information is generated. This DWARF information is important for the profiler to be able - to map instructions back to source line locations. + to map instructions back to source line locations. The usefulness of this + DWARF information can be improved with the ``-fdebug-info-for-profiling`` + and ``-funique-internal-linkage-names`` options. - On Linux, ``-g`` or just ``-gline-tables-only`` is sufficient: + On Linux: .. code-block:: console - $ clang++ -O2 -gline-tables-only code.cc -o code + $ clang++ -O2 -gline-tables-only \ + -fdebug-info-for-profiling -funique-internal-linkage-names \ + code.cc -o code While MSVC-style targets default to CodeView debug information, DWARF debug information is required to generate source-level LLVM profiles. Use ``-gdwarf`` to include DWARF debug information: - .. code-block:: console + .. code-block:: winbatch + + > clang-cl /O2 -gdwarf -gline-tables-only ^ + /clang:-fdebug-info-for-profiling /clang:-funique-internal-linkage-names ^ + code.cc /Fe:code /fuse-ld=lld /link /debug:dwarf - $ clang-cl -O2 -gdwarf -gline-tables-only coff-profile.cpp -fuse-ld=lld -link -debug:dwarf +.. note:: + + :ref:`-funique-internal-linkage-names ` + generates unique names based on given command-line source file paths. If + your build system uses absolute source paths and these paths may change + between steps 1 and 4, then the uniqued function names may change and result + in unused profile data. Consider omitting this option in such cases. 2. Run the executable under a sampling profiler. The specific profiler you use does not really matter, as long as its output can be converted into the format that the LLVM optimizer understands. - Two such profilers are the the Linux Perf profiler + Two such profilers are the Linux Perf profiler (https://perf.wiki.kernel.org/) and Intel's Sampling Enabling Product (SEP), available as part of `Intel VTune `_. @@ -2482,7 +2500,9 @@ usual build cycle when using sample profilers for optimization: .. code-block:: console - $ perf record -b ./code + $ perf record -b -e BR_INST_RETIRED.NEAR_TAKEN:uppp ./code + + If the event above is unavailable, ``branches:u`` is probably next-best. Note the use of the ``-b`` flag. This tells Perf to use the Last Branch Record (LBR) to record call chains. While this is not strictly required, @@ -2532,21 +2552,42 @@ usual build cycle when using sample profilers for optimization: that executes faster than the original one. Note that you are not required to build the code with the exact same arguments that you used in the first step. The only requirement is that you build the code - with ``-gline-tables-only`` and ``-fprofile-sample-use``. + with the same debug info options and ``-fprofile-sample-use``. + + On Linux: .. code-block:: console - $ clang++ -O2 -gline-tables-only -fprofile-sample-use=code.prof code.cc -o code + $ clang++ -O2 -gline-tables-only \ + -fdebug-info-for-profiling -funique-internal-linkage-names \ + -fprofile-sample-use=code.prof code.cc -o code - [OPTIONAL] Sampling-based profiles can have inaccuracies or missing block/ - edge counters. The profile inference algorithm (profi) can be used to infer - missing blocks and edge counts, and improve the quality of profile data. - Enable it with ``-fsample-profile-use-profi``. + On Windows: - .. code-block:: console + .. code-block:: winbatch + + > clang-cl /O2 -gdwarf -gline-tables-only ^ + /clang:-fdebug-info-for-profiling /clang:-funique-internal-linkage-names ^ + /fprofile-sample-use=code.prof code.cc /Fe:code /fuse-ld=lld /link /debug:dwarf + + [OPTIONAL] Sampling-based profiles can have inaccuracies or missing block/ + edge counters. The profile inference algorithm (profi) can be used to infer + missing blocks and edge counts, and improve the quality of profile data. + Enable it with ``-fsample-profile-use-profi``. For example, on Linux: + + .. code-block:: console + + $ clang++ -fsample-profile-use-profi -O2 -gline-tables-only \ + -fdebug-info-for-profiling -funique-internal-linkage-names \ + -fprofile-sample-use=code.prof code.cc -o code + + On Windows: + + .. code-block:: winbatch - $ clang++ -O2 -gline-tables-only -fprofile-sample-use=code.prof \ - -fsample-profile-use-profi code.cc -o code + > clang-cl /clang:-fsample-profile-use-profi /O2 -gdwarf -gline-tables-only ^ + /clang:-fdebug-info-for-profiling /clang:-funique-internal-linkage-names ^ + /fprofile-sample-use=code.prof code.cc /Fe:code /fuse-ld=lld /link /debug:dwarf Sample Profile Formats """""""""""""""""""""" diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst index fb748d23a53d01ce04c607f38d605c3ac7b26de8..0d87df36ced0e91fdd6953ca4e5e352ea5e16c4d 100644 --- a/clang/docs/analyzer/checkers.rst +++ b/clang/docs/analyzer/checkers.rst @@ -1462,6 +1462,99 @@ checker). Default value of the option is ``true``. +.. _unix-Stream: + +unix.Stream (C) +""""""""""""""" +Check C stream handling functions: +``fopen, fdopen, freopen, tmpfile, fclose, fread, fwrite, fgetc, fgets, fputc, fputs, fprintf, fscanf, ungetc, getdelim, getline, fseek, fseeko, ftell, ftello, fflush, rewind, fgetpos, fsetpos, clearerr, feof, ferror, fileno``. + +The checker maintains information about the C stream objects (``FILE *``) and +can detect error conditions related to use of streams. The following conditions +are detected: + +* The ``FILE *`` pointer passed to the function is NULL (the single exception is + ``fflush`` where NULL is allowed). +* Use of stream after close. +* Opened stream is not closed. +* Read from a stream after end-of-file. (This is not a fatal error but reported + by the checker. Stream remains in EOF state and the read operation fails.) +* Use of stream when the file position is indeterminate after a previous failed + operation. Some functions (like ``ferror``, ``clearerr``, ``fseek``) are + allowed in this state. +* Invalid 3rd ("``whence``") argument to ``fseek``. + +The stream operations are by this checker usually split into two cases, a success +and a failure case. However, in the case of write operations (like ``fwrite``, +``fprintf`` and even ``fsetpos``) this behavior could produce a large amount of +unwanted reports on projects that don't have error checks around the write +operations, so by default the checker assumes that write operations always succeed. +This behavior can be controlled by the ``Pedantic`` flag: With +``-analyzer-config unix.Stream:Pedantic=true`` the checker will model the +cases where a write operation fails and report situations where this leads to +erroneous behavior. (The default is ``Pedantic=false``, where write operations +are assumed to succeed.) + +.. code-block:: c + + void test1() { + FILE *p = fopen("foo", "r"); + } // warn: opened file is never closed + + void test2() { + FILE *p = fopen("foo", "r"); + fseek(p, 1, SEEK_SET); // warn: stream pointer might be NULL + fclose(p); + } + + void test3() { + FILE *p = fopen("foo", "r"); + if (p) { + fseek(p, 1, 3); // warn: third arg should be SEEK_SET, SEEK_END, or SEEK_CUR + fclose(p); + } + } + + void test4() { + FILE *p = fopen("foo", "r"); + if (!p) + return; + + fclose(p); + fclose(p); // warn: stream already closed + } + + void test5() { + FILE *p = fopen("foo", "r"); + if (!p) + return; + + fgetc(p); + if (!ferror(p)) + fgetc(p); // warn: possible read after end-of-file + + fclose(p); + } + + void test6() { + FILE *p = fopen("foo", "r"); + if (!p) + return; + + fgetc(p); + if (!feof(p)) + fgetc(p); // warn: file position may be indeterminate after I/O error + + fclose(p); + } + +**Limitations** + +The checker does not track the correspondence between integer file descriptors +and ``FILE *`` pointers. Operations on standard streams like ``stdin`` are not +treated specially and are therefore often not recognized (because these streams +are usually not opened explicitly by the program, and are global variables). + .. _osx-checkers: osx @@ -3116,99 +3209,6 @@ Check for misuses of stream APIs. Check for misuses of stream APIs: ``fopen, fcl fclose(F); // warn: closing a previously closed file stream } -.. _alpha-unix-Stream: - -alpha.unix.Stream (C) -""""""""""""""""""""" -Check C stream handling functions: -``fopen, fdopen, freopen, tmpfile, fclose, fread, fwrite, fgetc, fgets, fputc, fputs, fprintf, fscanf, ungetc, getdelim, getline, fseek, fseeko, ftell, ftello, fflush, rewind, fgetpos, fsetpos, clearerr, feof, ferror, fileno``. - -The checker maintains information about the C stream objects (``FILE *``) and -can detect error conditions related to use of streams. The following conditions -are detected: - -* The ``FILE *`` pointer passed to the function is NULL (the single exception is - ``fflush`` where NULL is allowed). -* Use of stream after close. -* Opened stream is not closed. -* Read from a stream after end-of-file. (This is not a fatal error but reported - by the checker. Stream remains in EOF state and the read operation fails.) -* Use of stream when the file position is indeterminate after a previous failed - operation. Some functions (like ``ferror``, ``clearerr``, ``fseek``) are - allowed in this state. -* Invalid 3rd ("``whence``") argument to ``fseek``. - -The stream operations are by this checker usually split into two cases, a success -and a failure case. However, in the case of write operations (like ``fwrite``, -``fprintf`` and even ``fsetpos``) this behavior could produce a large amount of -unwanted reports on projects that don't have error checks around the write -operations, so by default the checker assumes that write operations always succeed. -This behavior can be controlled by the ``Pedantic`` flag: With -``-analyzer-config alpha.unix.Stream:Pedantic=true`` the checker will model the -cases where a write operation fails and report situations where this leads to -erroneous behavior. (The default is ``Pedantic=false``, where write operations -are assumed to succeed.) - -.. code-block:: c - - void test1() { - FILE *p = fopen("foo", "r"); - } // warn: opened file is never closed - - void test2() { - FILE *p = fopen("foo", "r"); - fseek(p, 1, SEEK_SET); // warn: stream pointer might be NULL - fclose(p); - } - - void test3() { - FILE *p = fopen("foo", "r"); - if (p) { - fseek(p, 1, 3); // warn: third arg should be SEEK_SET, SEEK_END, or SEEK_CUR - fclose(p); - } - } - - void test4() { - FILE *p = fopen("foo", "r"); - if (!p) - return; - - fclose(p); - fclose(p); // warn: stream already closed - } - - void test5() { - FILE *p = fopen("foo", "r"); - if (!p) - return; - - fgetc(p); - if (!ferror(p)) - fgetc(p); // warn: possible read after end-of-file - - fclose(p); - } - - void test6() { - FILE *p = fopen("foo", "r"); - if (!p) - return; - - fgetc(p); - if (!feof(p)) - fgetc(p); // warn: file position may be indeterminate after I/O error - - fclose(p); - } - -**Limitations** - -The checker does not track the correspondence between integer file descriptors -and ``FILE *`` pointers. Operations on standard streams like ``stdin`` are not -treated specially and are therefore often not recognized (because these streams -are usually not opened explicitly by the program, and are global variables). - .. _alpha-unix-cstring-BufferOverlap: alpha.unix.cstring.BufferOverlap (C) diff --git a/clang/include/clang/AST/ASTNodeTraverser.h b/clang/include/clang/AST/ASTNodeTraverser.h index 216dc9eef08b62c87cde4d19d5af36c2f2680562..bf7c204e4ad73ab6408292215d3a839cc495c0ca 100644 --- a/clang/include/clang/AST/ASTNodeTraverser.h +++ b/clang/include/clang/AST/ASTNodeTraverser.h @@ -844,6 +844,12 @@ public: } } + void VisitUnresolvedLookupExpr(const UnresolvedLookupExpr *E) { + if (E->hasExplicitTemplateArgs()) + for (auto Arg : E->template_arguments()) + Visit(Arg.getArgument()); + } + void VisitRequiresExpr(const RequiresExpr *E) { for (auto *D : E->getLocalParameters()) Visit(D); diff --git a/clang/include/clang/AST/DeclContextInternals.h b/clang/include/clang/AST/DeclContextInternals.h index c4734ab578953835ee9719264ae2e9279d7d979f..e169c4859219290f483d59eb5aafb5bb99fa591b 100644 --- a/clang/include/clang/AST/DeclContextInternals.h +++ b/clang/include/clang/AST/DeclContextInternals.h @@ -42,11 +42,12 @@ class StoredDeclsList { /// external declarations. DeclsAndHasExternalTy Data; - template - void erase_if(Fn ShouldErase) { + template DeclListNode::Decls *erase_if(Fn ShouldErase) { Decls List = Data.getPointer(); + if (!List) - return; + return nullptr; + ASTContext &C = getASTContext(); DeclListNode::Decls NewHead = nullptr; DeclListNode::Decls *NewLast = nullptr; @@ -79,6 +80,17 @@ class StoredDeclsList { Data.setPointer(NewHead); assert(llvm::none_of(getLookupResult(), ShouldErase) && "Still exists!"); + + if (!Data.getPointer()) + // All declarations are erased. + return nullptr; + else if (NewHead.is()) + // The list only contains a declaration, the header itself. + return (DeclListNode::Decls *)&Data; + else { + assert(NewLast && NewLast->is() && "Not the tail?"); + return NewLast; + } } void erase(NamedDecl *ND) { @@ -160,12 +172,16 @@ public: void replaceExternalDecls(ArrayRef Decls) { // Remove all declarations that are either external or are replaced with - // external declarations. - erase_if([Decls](NamedDecl *ND) { + // external declarations with higher visibilities. + DeclListNode::Decls *Tail = erase_if([Decls](NamedDecl *ND) { if (ND->isFromASTFile()) return true; + // FIXME: Can we get rid of this loop completely? for (NamedDecl *D : Decls) - if (D->declarationReplaces(ND, /*IsKnownNewer=*/false)) + // Only replace the local declaration if the external declaration has + // higher visibilities. + if (D->getModuleOwnershipKind() <= ND->getModuleOwnershipKind() && + D->declarationReplaces(ND, /*IsKnownNewer=*/false)) return true; return false; }); @@ -185,24 +201,15 @@ public: DeclsAsList = Node; } - DeclListNode::Decls Head = Data.getPointer(); - if (Head.isNull()) { + if (!Data.getPointer()) { Data.setPointer(DeclsAsList); return; } - // Find the end of the existing list. - // FIXME: It would be possible to preserve information from erase_if to - // avoid this rescan looking for the end of the list. - DeclListNode::Decls *Tail = &Head; - while (DeclListNode *Node = Tail->dyn_cast()) - Tail = &Node->Rest; - // Append the Decls. DeclListNode *Node = C.AllocateDeclListNode(Tail->get()); Node->Rest = DeclsAsList; *Tail = Node; - Data.setPointer(Head); } /// Return the list of all the decls. diff --git a/clang/include/clang/AST/ExprCXX.h b/clang/include/clang/AST/ExprCXX.h index a915745d2d7322c7bf34321d0f69b6b40fb6c4ce..ab3f810b45192b5ca9e98b734aa872ab1402c48d 100644 --- a/clang/include/clang/AST/ExprCXX.h +++ b/clang/include/clang/AST/ExprCXX.h @@ -1482,6 +1482,8 @@ public: /// const S &s_ref = S(); // Requires a CXXBindTemporaryExpr. /// } /// \endcode +/// +/// Destructor might be null if destructor declaration is not valid. class CXXBindTemporaryExpr : public Expr { CXXTemporary *Temp = nullptr; Stmt *SubExpr = nullptr; diff --git a/clang/include/clang/AST/NestedNameSpecifier.h b/clang/include/clang/AST/NestedNameSpecifier.h index 7b0c21b9e7cfb1515789809bee50566bedbad480..a1d9e30e660d143610d3fdd22fcfcecff3443476 100644 --- a/clang/include/clang/AST/NestedNameSpecifier.h +++ b/clang/include/clang/AST/NestedNameSpecifier.h @@ -266,7 +266,7 @@ public: explicit operator bool() const { return Qualifier; } /// Evaluates true when this nested-name-specifier location is - /// empty. + /// non-empty. bool hasQualifier() const { return Qualifier; } /// Retrieve the nested-name-specifier to which this instance diff --git a/clang/include/clang/AST/OpenACCClause.h b/clang/include/clang/AST/OpenACCClause.h index 277a351c49fcb89335c19845262643986a9de157..bb4cb1f5d5080bd33103645e267b1e948e91d6ca 100644 --- a/clang/include/clang/AST/OpenACCClause.h +++ b/clang/include/clang/AST/OpenACCClause.h @@ -156,51 +156,50 @@ public: Expr *ConditionExpr, SourceLocation EndLoc); }; -/// Represents a clause that has one or more IntExprs. It does not own the -/// IntExprs, but provides 'children' and other accessors. -class OpenACCClauseWithIntExprs : public OpenACCClauseWithParams { - MutableArrayRef IntExprs; +/// Represents a clause that has one or more expressions associated with it. +class OpenACCClauseWithExprs : public OpenACCClauseWithParams { + MutableArrayRef Exprs; protected: - OpenACCClauseWithIntExprs(OpenACCClauseKind K, SourceLocation BeginLoc, - SourceLocation LParenLoc, SourceLocation EndLoc) + OpenACCClauseWithExprs(OpenACCClauseKind K, SourceLocation BeginLoc, + SourceLocation LParenLoc, SourceLocation EndLoc) : OpenACCClauseWithParams(K, BeginLoc, LParenLoc, EndLoc) {} /// Used only for initialization, the leaf class can initialize this to /// trailing storage. - void setIntExprs(MutableArrayRef NewIntExprs) { - assert(IntExprs.empty() && "Cannot change IntExprs list"); - IntExprs = NewIntExprs; + void setExprs(MutableArrayRef NewExprs) { + assert(Exprs.empty() && "Cannot change Exprs list"); + Exprs = NewExprs; } - /// Gets the entire list of integer expressions, but leave it to the + /// Gets the entire list of expressions, but leave it to the /// individual clauses to expose this how they'd like. - llvm::ArrayRef getIntExprs() const { return IntExprs; } + llvm::ArrayRef getExprs() const { return Exprs; } public: child_range children() { - return child_range(reinterpret_cast(IntExprs.begin()), - reinterpret_cast(IntExprs.end())); + return child_range(reinterpret_cast(Exprs.begin()), + reinterpret_cast(Exprs.end())); } const_child_range children() const { child_range Children = - const_cast(this)->children(); + const_cast(this)->children(); return const_child_range(Children.begin(), Children.end()); } }; class OpenACCNumGangsClause final - : public OpenACCClauseWithIntExprs, + : public OpenACCClauseWithExprs, public llvm::TrailingObjects { OpenACCNumGangsClause(SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef IntExprs, SourceLocation EndLoc) - : OpenACCClauseWithIntExprs(OpenACCClauseKind::NumGangs, BeginLoc, - LParenLoc, EndLoc) { + : OpenACCClauseWithExprs(OpenACCClauseKind::NumGangs, BeginLoc, LParenLoc, + EndLoc) { std::uninitialized_copy(IntExprs.begin(), IntExprs.end(), getTrailingObjects()); - setIntExprs(MutableArrayRef(getTrailingObjects(), IntExprs.size())); + setExprs(MutableArrayRef(getTrailingObjects(), IntExprs.size())); } public: @@ -209,35 +208,35 @@ public: ArrayRef IntExprs, SourceLocation EndLoc); llvm::ArrayRef getIntExprs() { - return OpenACCClauseWithIntExprs::getIntExprs(); + return OpenACCClauseWithExprs::getExprs(); } llvm::ArrayRef getIntExprs() const { - return OpenACCClauseWithIntExprs::getIntExprs(); + return OpenACCClauseWithExprs::getExprs(); } }; /// Represents one of a handful of clauses that have a single integer /// expression. -class OpenACCClauseWithSingleIntExpr : public OpenACCClauseWithIntExprs { +class OpenACCClauseWithSingleIntExpr : public OpenACCClauseWithExprs { Expr *IntExpr; protected: OpenACCClauseWithSingleIntExpr(OpenACCClauseKind K, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc) - : OpenACCClauseWithIntExprs(K, BeginLoc, LParenLoc, EndLoc), + : OpenACCClauseWithExprs(K, BeginLoc, LParenLoc, EndLoc), IntExpr(IntExpr) { - setIntExprs(MutableArrayRef{&this->IntExpr, 1}); + setExprs(MutableArrayRef{&this->IntExpr, 1}); } public: - bool hasIntExpr() const { return !getIntExprs().empty(); } + bool hasIntExpr() const { return !getExprs().empty(); } const Expr *getIntExpr() const { - return hasIntExpr() ? getIntExprs()[0] : nullptr; + return hasIntExpr() ? getExprs()[0] : nullptr; } - Expr *getIntExpr() { return hasIntExpr() ? getIntExprs()[0] : nullptr; }; + Expr *getIntExpr() { return hasIntExpr() ? getExprs()[0] : nullptr; }; }; class OpenACCNumWorkersClause : public OpenACCClauseWithSingleIntExpr { @@ -261,6 +260,40 @@ public: Expr *IntExpr, SourceLocation EndLoc); }; +/// Represents a clause with one or more 'var' objects, represented as an expr, +/// as its arguments. Var-list is expected to be stored in trailing storage. +/// For now, we're just storing the original expression in its entirety, unlike +/// OMP which has to do a bunch of work to create a private. +class OpenACCClauseWithVarList : public OpenACCClauseWithExprs { +protected: + OpenACCClauseWithVarList(OpenACCClauseKind K, SourceLocation BeginLoc, + SourceLocation LParenLoc, SourceLocation EndLoc) + : OpenACCClauseWithExprs(K, BeginLoc, LParenLoc, EndLoc) {} + +public: + ArrayRef getVarList() { return getExprs(); } + ArrayRef getVarList() const { return getExprs(); } +}; + +class OpenACCPrivateClause final + : public OpenACCClauseWithVarList, + public llvm::TrailingObjects { + + OpenACCPrivateClause(SourceLocation BeginLoc, SourceLocation LParenLoc, + ArrayRef VarList, SourceLocation EndLoc) + : OpenACCClauseWithVarList(OpenACCClauseKind::Private, BeginLoc, + LParenLoc, EndLoc) { + std::uninitialized_copy(VarList.begin(), VarList.end(), + getTrailingObjects()); + setExprs(MutableArrayRef(getTrailingObjects(), VarList.size())); + } + +public: + static OpenACCPrivateClause * + Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, + ArrayRef VarList, SourceLocation EndLoc); +}; + template class OpenACCClauseVisitor { Impl &getDerived() { return static_cast(*this); } @@ -299,6 +332,9 @@ public: class OpenACCClausePrinter final : public OpenACCClauseVisitor { raw_ostream &OS; + const PrintingPolicy &Policy; + + void printExpr(const Expr *E); public: void VisitClauseList(ArrayRef List) { @@ -309,7 +345,8 @@ public: OS << ' '; } } - OpenACCClausePrinter(raw_ostream &OS) : OS(OS) {} + OpenACCClausePrinter(raw_ostream &OS, const PrintingPolicy &Policy) + : OS(OS), Policy(Policy) {} #define VISIT_CLAUSE(CLAUSE_NAME) \ void Visit##CLAUSE_NAME##Clause(const OpenACC##CLAUSE_NAME##Clause &Clause); diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h index dff02d4861b3dbd5272b9c238a8d4604b58d4ab9..e6643469e0b3344937d69beeee77e37d8bfed37e 100644 --- a/clang/include/clang/AST/Type.h +++ b/clang/include/clang/AST/Type.h @@ -480,7 +480,7 @@ public: } void removeCVRQualifiers(unsigned mask) { assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits"); - Mask &= ~mask; + Mask &= ~static_cast(mask); } void removeCVRQualifiers() { removeCVRQualifiers(CVRMask); @@ -609,7 +609,7 @@ public: } void removeFastQualifiers(unsigned mask) { assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"); - Mask &= ~mask; + Mask &= ~static_cast(mask); } void removeFastQualifiers() { removeFastQualifiers(FastMask); @@ -2378,6 +2378,10 @@ public: /// 'riscv_rvv_vector_bits' type attribute as VectorType. QualType getRVVEltType(const ASTContext &Ctx) const; + /// Returns the representative type for the element of a sizeless vector + /// builtin type. + QualType getSizelessVectorEltType(const ASTContext &Ctx) const; + /// Types are partitioned into 3 broad categories (C99 6.2.5p1): /// object types, function types, and incomplete types. diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td index 4408d517e70e5883f1e68357a3fde364aaaf6b59..0225598cbbe8ad8f1d5e8085688e22fda4ef75b1 100644 --- a/clang/include/clang/Basic/Attr.td +++ b/clang/include/clang/Basic/Attr.td @@ -592,6 +592,49 @@ class AttrSubjectMatcherAggregateRule { def SubjectMatcherForNamed : AttrSubjectMatcherAggregateRule; +// Enumeration specifying what kind of behavior should be used for late +// parsing of attributes. +class LateAttrParseKind { + int Kind = val; +} + +// Never late parsed +def LateAttrParseNever : LateAttrParseKind<0>; + +// Standard late attribute parsing +// +// This is language dependent. For example: +// +// * For C++ enables late parsing of a declaration attributes +// * For C does not enable late parsing of attributes +// +def LateAttrParseStandard : LateAttrParseKind<1>; + +// Experimental extension to standard late attribute parsing +// +// This extension behaves like `LateAttrParseStandard` but allows +// late parsing attributes in more contexts. +// +// In contexts where `LateAttrParseStandard` attributes are late +// parsed, `LateAttrParseExperimentalExt` attributes will also +// be late parsed. +// +// In contexts that only late parse `LateAttrParseExperimentalExt` attributes +// (see `LateParsedAttrList::lateAttrParseExperimentalExtOnly()`) +// +// * If `-fexperimental-late-parse-attributes` +// (`LangOpts.ExperimentalLateParseAttributes`) is enabled the attribute +// will be late parsed. +// * If `-fexperimental-late-parse-attributes` +// (`LangOpts.ExperimentalLateParseAttributes`) is disabled the attribute +// will **not** be late parsed (i.e parsed immediately). +// +// The following contexts are supported: +// +// * TODO: Add contexts here when they are implemented. +// +def LateAttrParseExperimentalExt : LateAttrParseKind<2>; + class Attr { // The various ways in which an attribute can be spelled in source list Spellings; @@ -603,8 +646,8 @@ class Attr { list Accessors = []; // Specify targets for spellings. list TargetSpecificSpellings = []; - // Set to true for attributes with arguments which require delayed parsing. - bit LateParsed = 0; + // Specifies the late parsing kind. + LateAttrParseKind LateParsed = LateAttrParseNever; // Set to false to prevent an attribute from being propagated from a template // to the instantiation. bit Clone = 1; @@ -3173,7 +3216,7 @@ def DiagnoseIf : InheritableAttr { BoolArgument<"ArgDependent", 0, /*fake*/ 1>, DeclArgument]; let InheritEvenIfAlreadyPresent = 1; - let LateParsed = 1; + let LateParsed = LateAttrParseStandard; let AdditionalMembers = [{ bool isError() const { return diagnosticType == DT_Error; } bool isWarning() const { return diagnosticType == DT_Warning; } @@ -3211,7 +3254,7 @@ def ObjCRequiresPropertyDefs : InheritableAttr { def Unused : InheritableAttr { let Spellings = [CXX11<"", "maybe_unused", 201603>, GCC<"unused">, C23<"", "maybe_unused", 202106>]; - let Subjects = SubjectList<[Var, ObjCIvar, Type, Enum, EnumConstant, Label, + let Subjects = SubjectList<[Var, Binding, ObjCIvar, Type, Enum, EnumConstant, Label, Field, ObjCMethod, FunctionLike]>; let Documentation = [WarnMaybeUnusedDocs]; } @@ -3472,7 +3515,7 @@ def AssertCapability : InheritableAttr { let Spellings = [Clang<"assert_capability", 0>, Clang<"assert_shared_capability", 0>]; let Subjects = SubjectList<[Function]>; - let LateParsed = 1; + let LateParsed = LateAttrParseStandard; let TemplateDependent = 1; let ParseArgumentsAsUnevaluated = 1; let InheritEvenIfAlreadyPresent = 1; @@ -3488,7 +3531,7 @@ def AcquireCapability : InheritableAttr { GNU<"exclusive_lock_function">, GNU<"shared_lock_function">]; let Subjects = SubjectList<[Function]>; - let LateParsed = 1; + let LateParsed = LateAttrParseStandard; let TemplateDependent = 1; let ParseArgumentsAsUnevaluated = 1; let InheritEvenIfAlreadyPresent = 1; @@ -3504,7 +3547,7 @@ def TryAcquireCapability : InheritableAttr { Clang<"try_acquire_shared_capability", 0>]; let Subjects = SubjectList<[Function], ErrorDiag>; - let LateParsed = 1; + let LateParsed = LateAttrParseStandard; let TemplateDependent = 1; let ParseArgumentsAsUnevaluated = 1; let InheritEvenIfAlreadyPresent = 1; @@ -3520,7 +3563,7 @@ def ReleaseCapability : InheritableAttr { Clang<"release_generic_capability", 0>, Clang<"unlock_function", 0>]; let Subjects = SubjectList<[Function]>; - let LateParsed = 1; + let LateParsed = LateAttrParseStandard; let TemplateDependent = 1; let ParseArgumentsAsUnevaluated = 1; let InheritEvenIfAlreadyPresent = 1; @@ -3539,7 +3582,7 @@ def RequiresCapability : InheritableAttr { Clang<"requires_shared_capability", 0>, Clang<"shared_locks_required", 0>]; let Args = [VariadicExprArgument<"Args">]; - let LateParsed = 1; + let LateParsed = LateAttrParseStandard; let TemplateDependent = 1; let ParseArgumentsAsUnevaluated = 1; let InheritEvenIfAlreadyPresent = 1; @@ -3559,7 +3602,7 @@ def NoThreadSafetyAnalysis : InheritableAttr { def GuardedBy : InheritableAttr { let Spellings = [GNU<"guarded_by">]; let Args = [ExprArgument<"Arg">]; - let LateParsed = 1; + let LateParsed = LateAttrParseStandard; let TemplateDependent = 1; let ParseArgumentsAsUnevaluated = 1; let InheritEvenIfAlreadyPresent = 1; @@ -3570,7 +3613,7 @@ def GuardedBy : InheritableAttr { def PtGuardedBy : InheritableAttr { let Spellings = [GNU<"pt_guarded_by">]; let Args = [ExprArgument<"Arg">]; - let LateParsed = 1; + let LateParsed = LateAttrParseStandard; let TemplateDependent = 1; let ParseArgumentsAsUnevaluated = 1; let InheritEvenIfAlreadyPresent = 1; @@ -3581,7 +3624,7 @@ def PtGuardedBy : InheritableAttr { def AcquiredAfter : InheritableAttr { let Spellings = [GNU<"acquired_after">]; let Args = [VariadicExprArgument<"Args">]; - let LateParsed = 1; + let LateParsed = LateAttrParseStandard; let TemplateDependent = 1; let ParseArgumentsAsUnevaluated = 1; let InheritEvenIfAlreadyPresent = 1; @@ -3592,7 +3635,7 @@ def AcquiredAfter : InheritableAttr { def AcquiredBefore : InheritableAttr { let Spellings = [GNU<"acquired_before">]; let Args = [VariadicExprArgument<"Args">]; - let LateParsed = 1; + let LateParsed = LateAttrParseStandard; let TemplateDependent = 1; let ParseArgumentsAsUnevaluated = 1; let InheritEvenIfAlreadyPresent = 1; @@ -3603,7 +3646,7 @@ def AcquiredBefore : InheritableAttr { def AssertExclusiveLock : InheritableAttr { let Spellings = [GNU<"assert_exclusive_lock">]; let Args = [VariadicExprArgument<"Args">]; - let LateParsed = 1; + let LateParsed = LateAttrParseStandard; let TemplateDependent = 1; let ParseArgumentsAsUnevaluated = 1; let InheritEvenIfAlreadyPresent = 1; @@ -3614,7 +3657,7 @@ def AssertExclusiveLock : InheritableAttr { def AssertSharedLock : InheritableAttr { let Spellings = [GNU<"assert_shared_lock">]; let Args = [VariadicExprArgument<"Args">]; - let LateParsed = 1; + let LateParsed = LateAttrParseStandard; let TemplateDependent = 1; let ParseArgumentsAsUnevaluated = 1; let InheritEvenIfAlreadyPresent = 1; @@ -3627,7 +3670,7 @@ def AssertSharedLock : InheritableAttr { def ExclusiveTrylockFunction : InheritableAttr { let Spellings = [GNU<"exclusive_trylock_function">]; let Args = [ExprArgument<"SuccessValue">, VariadicExprArgument<"Args">]; - let LateParsed = 1; + let LateParsed = LateAttrParseStandard; let TemplateDependent = 1; let ParseArgumentsAsUnevaluated = 1; let InheritEvenIfAlreadyPresent = 1; @@ -3640,7 +3683,7 @@ def ExclusiveTrylockFunction : InheritableAttr { def SharedTrylockFunction : InheritableAttr { let Spellings = [GNU<"shared_trylock_function">]; let Args = [ExprArgument<"SuccessValue">, VariadicExprArgument<"Args">]; - let LateParsed = 1; + let LateParsed = LateAttrParseStandard; let TemplateDependent = 1; let ParseArgumentsAsUnevaluated = 1; let InheritEvenIfAlreadyPresent = 1; @@ -3651,7 +3694,7 @@ def SharedTrylockFunction : InheritableAttr { def LockReturned : InheritableAttr { let Spellings = [GNU<"lock_returned">]; let Args = [ExprArgument<"Arg">]; - let LateParsed = 1; + let LateParsed = LateAttrParseStandard; let TemplateDependent = 1; let ParseArgumentsAsUnevaluated = 1; let Subjects = SubjectList<[Function]>; @@ -3661,7 +3704,7 @@ def LockReturned : InheritableAttr { def LocksExcluded : InheritableAttr { let Spellings = [GNU<"locks_excluded">]; let Args = [VariadicExprArgument<"Args">]; - let LateParsed = 1; + let LateParsed = LateAttrParseStandard; let TemplateDependent = 1; let ParseArgumentsAsUnevaluated = 1; let InheritEvenIfAlreadyPresent = 1; diff --git a/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td b/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td index 91a40cd589b385d3adb8eefbc17bca90fabd0491..6896e0f5aa593c2e598bec39e2b331a089352bce 100644 --- a/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td +++ b/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td @@ -24,7 +24,7 @@ def err_no_matching_target : Error<"no matching target found for target variant def err_unsupported_vendor : Error<"vendor '%0' is not supported: '%1'">; def err_unsupported_environment : Error<"environment '%0' is not supported: '%1'">; def err_unsupported_os : Error<"os '%0' is not supported: '%1'">; -def err_cannot_read_alias_list : Error<"could not read alias list '%0': %1">; +def err_cannot_read_input_list : Error<"could not read %select{alias list|filelist}0 '%1': %2">; } // end of command line category. let CategoryName = "Verification" in { diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td b/clang/include/clang/Basic/DiagnosticParseKinds.td index 38174cf3549f14ecad83883acff62b47f15b92c0..44bc4e0e130de839e280b3f14c75aead99586bf8 100644 --- a/clang/include/clang/Basic/DiagnosticParseKinds.td +++ b/clang/include/clang/Basic/DiagnosticParseKinds.td @@ -478,6 +478,15 @@ def ext_decomp_decl_empty : ExtWarn< "ISO C++17 does not allow a decomposition group to be empty">, InGroup>; +// C++26 structured bindings +def ext_decl_attrs_on_binding : ExtWarn< + "an attribute specifier sequence attached to a structured binding declaration " + "is a C++2c extension">, InGroup; +def warn_cxx23_compat_decl_attrs_on_binding : Warning< + "an attribute specifier sequence attached to a structured binding declaration " + "is incompatible with C++ standards before C++2c">, + InGroup, DefaultIgnore; + /// Objective-C parser diagnostics def err_expected_minus_or_plus : Error< "method type specifier must start with '-' or '+'">; @@ -1429,6 +1438,9 @@ def err_omp_decl_in_declare_simd_variant : Error< def err_omp_sink_and_source_iteration_not_allowd: Error<" '%0 %select{sink:|source:}1' must be with '%select{omp_cur_iteration - 1|omp_cur_iteration}1'">; def err_omp_unknown_map_type : Error< "incorrect map type, expected one of 'to', 'from', 'tofrom', 'alloc', 'release', or 'delete'">; +def err_omp_more_one_map_type : Error<"map type is already specified">; +def note_previous_map_type_specified_here + : Note<"map type '%0' is previous specified here">; def err_omp_unknown_map_type_modifier : Error< "incorrect map type modifier, expected one of: 'always', 'close', 'mapper'" "%select{|, 'present'|, 'present', 'iterator'}0%select{|, 'ompx_hold'}1">; @@ -1436,6 +1448,8 @@ def err_omp_map_type_missing : Error< "missing map type">; def err_omp_map_type_modifier_missing : Error< "missing map type modifier">; +def err_omp_map_modifier_specification_list : Error< + "empty modifier-specification-list is not allowed">; def err_omp_declare_simd_inbranch_notinbranch : Error< "unexpected '%0' clause, '%1' is specified already">; def err_omp_expected_clause_argument diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index fdca82934cb4dcf0b78130377f846d60b24eb987..4b074b853bfe65b82a78ca90fbfc00dbf82c932a 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -307,6 +307,8 @@ def err_invalid_vector_long_long_decl_spec : Error < "POWER7 or later) to be enabled">; def err_invalid_vector_long_double_decl_spec : Error< "cannot use 'long double' with '__vector'">; +def err_invalid_vector_complex_decl_spec : Error< + "cannot use '_Complex' with '__vector'">; def warn_vector_long_decl_spec_combination : Warning< "Use of 'long' with '__vector' is deprecated">, InGroup; @@ -9901,6 +9903,9 @@ def warn_format_invalid_annotation : Warning< def warn_format_P_no_precision : Warning< "using '%%P' format specifier without precision">, InGroup; +def warn_format_P_with_objc_pointer : Warning< + "using '%%P' format specifier with an Objective-C pointer results in dumping runtime object structure, not object value">, + InGroup; def warn_printf_ignored_flag: Warning< "flag '%0' is ignored when flag '%1' is present">, InGroup; @@ -9950,6 +9955,8 @@ def warn_ret_stack_addr_ref : Warning< def warn_ret_local_temp_addr_ref : Warning< "returning %select{address of|reference to}0 local temporary object">, InGroup; +def err_ret_local_temp_ref : Error< + "returning reference to local temporary object">; def warn_ret_addr_label : Warning< "returning address of label, which is local">, InGroup; @@ -10328,9 +10335,13 @@ def err_shufflevector_nonconstant_argument : Error< def err_shufflevector_argument_too_large : Error< "index for __builtin_shufflevector must be less than the total number " "of vector elements">; +def err_shufflevector_minus_one_is_undefined_behavior_constexpr : Error< + "index for __builtin_shufflevector not within the bounds of the input vectors; index of -1 found at position %0 not permitted in a constexpr context.">; def err_convertvector_non_vector : Error< "first argument to __builtin_convertvector must be a vector">; +def err_convertvector_constexpr_unsupported_vector_cast : Error< + "unsupported vector cast from %0 to %1 in a constant expression.">; def err_builtin_non_vector_type : Error< "%0 argument to %1 must be of vector type">; def err_convertvector_incompatible_vector : Error< @@ -12296,4 +12307,7 @@ def err_acc_num_gangs_num_args "OpenACC 'num_gangs' " "%select{|clause: '%1' directive expects maximum of %2, %3 were " "provided}0">; +def err_acc_not_a_var_ref + : Error<"OpenACC variable is not a valid variable name, sub-array, array " + "element, or composite variable member">; } // end of sema component. diff --git a/clang/include/clang/Basic/LangOptions.def b/clang/include/clang/Basic/LangOptions.def index 8ef6700ecdc78eca7ec8a245d37d5d49122dd0d6..55c81eab1ec1508f75fef5d2def123ac1196bbc6 100644 --- a/clang/include/clang/Basic/LangOptions.def +++ b/clang/include/clang/Basic/LangOptions.def @@ -164,6 +164,7 @@ LANGOPT(ExperimentalLibrary, 1, 0, "enable unstable and experimental library fea LANGOPT(PointerAuthIntrinsics, 1, 0, "pointer authentication intrinsics") LANGOPT(DoubleSquareBracketAttributes, 1, 0, "'[[]]' attributes extension for all language standard modes") +LANGOPT(ExperimentalLateParseAttributes, 1, 0, "experimental late parsing of attributes") COMPATIBLE_LANGOPT(RecoveryAST, 1, 1, "Preserve expressions in AST when encountering errors") COMPATIBLE_LANGOPT(RecoveryASTType, 1, 1, "Preserve the type in recovery expressions") diff --git a/clang/include/clang/Basic/OpenACCClauses.def b/clang/include/clang/Basic/OpenACCClauses.def index dd5792e7ca8c39c33492a8cc64c4cbd5d041970f..6c3c2db66ef0cf468cb7dabfbe8e31402a6192e8 100644 --- a/clang/include/clang/Basic/OpenACCClauses.def +++ b/clang/include/clang/Basic/OpenACCClauses.def @@ -20,6 +20,7 @@ VISIT_CLAUSE(If) VISIT_CLAUSE(Self) VISIT_CLAUSE(NumGangs) VISIT_CLAUSE(NumWorkers) +VISIT_CLAUSE(Private) VISIT_CLAUSE(VectorLength) #undef VISIT_CLAUSE diff --git a/clang/include/clang/Basic/arm_neon.td b/clang/include/clang/Basic/arm_neon.td index 6d655c39360d3beaa76fc2198f13cf31f85d4bc8..6390ba3f9fe5e50252da63f247b1c8ed17cea451 100644 --- a/clang/include/clang/Basic/arm_neon.td +++ b/clang/include/clang/Basic/arm_neon.td @@ -275,7 +275,7 @@ def OP_VCVT_BF16_F32_HI_A32 (call "vget_low", $p0))>; def OP_CVT_F32_BF16 - : Op<(bitcast "R", (op "<<", (bitcast "int32_t", $p0), + : Op<(bitcast "R", (op "<<", (cast "int32_t", (bitcast "int16_t", $p0)), (literal "int32_t", "16")))>; //===----------------------------------------------------------------------===// diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index 5a6526b0592f7ba40ffad7c95bbc4914bcc21f43..864da4e1157f7da167feeb4e04613f7271ee6408 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -603,7 +603,6 @@ class MarshallingInfoVisibility // Key paths that are constant during parsing of options with the same key path prefix. defvar cplusplus = LangOpts<"CPlusPlus">; defvar cpp11 = LangOpts<"CPlusPlus11">; -defvar cpp14 = LangOpts<"CPlusPlus14">; defvar cpp17 = LangOpts<"CPlusPlus17">; defvar cpp20 = LangOpts<"CPlusPlus20">; defvar c99 = LangOpts<"C99">; @@ -1609,6 +1608,13 @@ defm double_square_bracket_attributes : BoolFOption<"double-square-bracket-attri LangOpts<"DoubleSquareBracketAttributes">, DefaultTrue, PosFlag, NegFlag>; +defm experimental_late_parse_attributes : BoolFOption<"experimental-late-parse-attributes", + LangOpts<"ExperimentalLateParseAttributes">, DefaultFalse, + PosFlag, + NegFlag, + BothFlags<[], [ClangOption, CC1Option], + " experimental late parsing of attributes">>; + defm autolink : BoolFOption<"autolink", CodeGenOpts<"Autolink">, DefaultTrue, NegFlag, Group, Group, HelpText<"Force linking the clang builtins runtime library">; + +/// ClangIR-specific options - BEGIN +defm clangir : BoolFOption<"clangir", + FrontendOpts<"UseClangIRPipeline">, DefaultFalse, + PosFlag, + NegFlag LLVM pipeline to compile">, + BothFlags<[], [ClangOption, CC1Option], "">>; +def emit_cir : Flag<["-"], "emit-cir">, Visibility<[CC1Option]>, + Group, HelpText<"Build ASTs and then lower to ClangIR">; +/// ClangIR-specific options - END + def flto_EQ : Joined<["-"], "flto=">, Visibility<[ClangOption, CLOption, CC1Option, FC1Option, FlangOption]>, Group, @@ -3371,9 +3388,10 @@ defm relaxed_template_template_args : BoolFOption<"relaxed-template-template-arg "Enable C++17 relaxed template template argument matching">, NegFlag>; defm sized_deallocation : BoolFOption<"sized-deallocation", - LangOpts<"SizedDeallocation">, Default, - PosFlag, - NegFlag, BothFlags<[], [ClangOption, CC1Option]>>; + LangOpts<"SizedDeallocation">, DefaultFalse, + PosFlag, + NegFlag>; defm aligned_allocation : BoolFOption<"aligned-allocation", LangOpts<"AlignedAllocation">, Default, PosFlag, @@ -4881,6 +4899,8 @@ def msimd128 : Flag<["-"], "msimd128">, Group; def mno_simd128 : Flag<["-"], "mno-simd128">, Group; def mrelaxed_simd : Flag<["-"], "mrelaxed-simd">, Group; def mno_relaxed_simd : Flag<["-"], "mno-relaxed-simd">, Group; +def mhalf_precision : Flag<["-"], "mhalf-precision">, Group; +def mno_half_precision : Flag<["-"], "mno-half-precision">, Group; def mnontrapping_fptoint : Flag<["-"], "mnontrapping-fptoint">, Group; def mno_nontrapping_fptoint : Flag<["-"], "mno-nontrapping-fptoint">, Group; def msign_ext : Flag<["-"], "msign-ext">, Group; @@ -6587,12 +6607,6 @@ def J : JoinedOrSeparate<["-"], "J">, Group, Alias; -let Visibility = [FlangOption] in { -def no_fortran_main : Flag<["-"], "fno-fortran-main">, - Visibility<[FlangOption]>, Group, - HelpText<"Do not include Fortran_main.a (provided by Flang) when linking">; -} // let Visibility = [ FlangOption ] - //===----------------------------------------------------------------------===// // FC1 Options //===----------------------------------------------------------------------===// diff --git a/clang/include/clang/Frontend/FrontendOptions.h b/clang/include/clang/Frontend/FrontendOptions.h index a738c1f375768282259993be13e40fcf6ce11ae0..bd4981ca0ac08cf2109649bfd5c22bc0169ce810 100644 --- a/clang/include/clang/Frontend/FrontendOptions.h +++ b/clang/include/clang/Frontend/FrontendOptions.h @@ -65,6 +65,9 @@ enum ActionKind { /// Translate input source into HTML. EmitHTML, + /// Emit a .cir file + EmitCIR, + /// Emit a .ll file. EmitLLVM, @@ -408,6 +411,10 @@ public: LLVM_PREFERRED_TYPE(bool) unsigned GenReducedBMI : 1; + /// Use Clang IR pipeline to emit code + LLVM_PREFERRED_TYPE(bool) + unsigned UseClangIRPipeline : 1; + CodeCompleteOptions CodeCompleteOpts; /// Specifies the output format of the AST. @@ -590,7 +597,7 @@ public: EmitSymbolGraph(false), EmitExtensionSymbolGraphs(false), EmitSymbolGraphSymbolLabelsForTesting(false), EmitPrettySymbolGraphs(false), GenReducedBMI(false), - TimeTraceGranularity(500) {} + UseClangIRPipeline(false), TimeTraceGranularity(500) {} /// getInputKindForExtension - Return the appropriate input kind for a file /// extension. For example, "c" would return Language::C. diff --git a/clang/include/clang/InstallAPI/FileList.h b/clang/include/clang/InstallAPI/FileList.h index 460af003b6a0ac4e0c345496186209226c1c8061..913734b8dc7c8824b1916f6ffaba6ba4c4a24f92 100644 --- a/clang/include/clang/InstallAPI/FileList.h +++ b/clang/include/clang/InstallAPI/FileList.h @@ -29,9 +29,10 @@ public: /// /// \param InputBuffer JSON input data. /// \param Destination Container to load headers into. + /// \param FM Optional File Manager to validate input files exist. static llvm::Error loadHeaders(std::unique_ptr InputBuffer, - HeaderSeq &Destination); + HeaderSeq &Destination, clang::FileManager *FM = nullptr); FileListReader() = delete; }; diff --git a/clang/include/clang/Parse/Parser.h b/clang/include/clang/Parse/Parser.h index fb117bf04087ee4e528ae19b4dcebccdda57ce44..daefd4f28f011aa9ece5088ea85e03d2133220e4 100644 --- a/clang/include/clang/Parse/Parser.h +++ b/clang/include/clang/Parse/Parser.h @@ -1398,12 +1398,21 @@ private: // A list of late-parsed attributes. Used by ParseGNUAttributes. class LateParsedAttrList: public SmallVector { public: - LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { } + LateParsedAttrList(bool PSoon = false, + bool LateAttrParseExperimentalExtOnly = false) + : ParseSoon(PSoon), + LateAttrParseExperimentalExtOnly(LateAttrParseExperimentalExtOnly) {} bool parseSoon() { return ParseSoon; } + /// returns true iff the attribute to be parsed should only be late parsed + /// if it is annotated with `LateAttrParseExperimentalExt` + bool lateAttrParseExperimentalExtOnly() { + return LateAttrParseExperimentalExtOnly; + } private: - bool ParseSoon; // Are we planning to parse these shortly after creation? + bool ParseSoon; // Are we planning to parse these shortly after creation? + bool LateAttrParseExperimentalExtOnly; }; /// Contains the lexed tokens of a member function definition @@ -3645,11 +3654,12 @@ private: ExprResult ParseOpenACCIDExpression(); /// Parses the variable list for the `cache` construct. void ParseOpenACCCacheVarList(); + + using OpenACCVarParseResult = std::pair; /// Parses a single variable in a variable list for OpenACC. - bool ParseOpenACCVar(); - /// Parses the variable list for the variety of clauses that take a var-list, - /// including the optional Special Token listed for some,based on clause type. - bool ParseOpenACCClauseVarList(OpenACCClauseKind Kind); + OpenACCVarParseResult ParseOpenACCVar(); + /// Parses the variable list for the variety of places that take a var-list. + llvm::SmallVector ParseOpenACCVarList(); /// Parses any parameters for an OpenACC Clause, including required/optional /// parens. OpenACCClauseParseResult diff --git a/clang/include/clang/Sema/DeclSpec.h b/clang/include/clang/Sema/DeclSpec.h index c9eecdafe62c7ce148f69dfbfca8f791e129112d..23bc780e04979d84cbd5d789fd6a4e3921b27696 100644 --- a/clang/include/clang/Sema/DeclSpec.h +++ b/clang/include/clang/Sema/DeclSpec.h @@ -36,6 +36,7 @@ #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ErrorHandling.h" +#include namespace clang { class ASTContext; @@ -1790,6 +1791,7 @@ public: struct Binding { IdentifierInfo *Name; SourceLocation NameLoc; + std::optional Attrs; }; private: @@ -1809,15 +1811,15 @@ public: : Bindings(nullptr), NumBindings(0), DeleteBindings(false) {} DecompositionDeclarator(const DecompositionDeclarator &G) = delete; DecompositionDeclarator &operator=(const DecompositionDeclarator &G) = delete; - ~DecompositionDeclarator() { - if (DeleteBindings) - delete[] Bindings; - } + ~DecompositionDeclarator() { clear(); } void clear() { LSquareLoc = RSquareLoc = SourceLocation(); if (DeleteBindings) delete[] Bindings; + else + llvm::for_each(llvm::MutableArrayRef(Bindings, NumBindings), + [](Binding &B) { B.Attrs.reset(); }); Bindings = nullptr; NumBindings = 0; DeleteBindings = false; @@ -2339,10 +2341,10 @@ public: } /// Set the decomposition bindings for this declarator. - void - setDecompositionBindings(SourceLocation LSquareLoc, - ArrayRef Bindings, - SourceLocation RSquareLoc); + void setDecompositionBindings( + SourceLocation LSquareLoc, + MutableArrayRef Bindings, + SourceLocation RSquareLoc); /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to /// EndLoc, which should be the last token of the chunk. diff --git a/clang/include/clang/Sema/Lookup.h b/clang/include/clang/Sema/Lookup.h index 0db5b847038ffdea0ef85bc81b1e3c11d8e1ff69..b0a08a05ac6a0ad8a4960afe44206a4067d27f07 100644 --- a/clang/include/clang/Sema/Lookup.h +++ b/clang/include/clang/Sema/Lookup.h @@ -499,7 +499,9 @@ public: /// Note that while no result was found in the current instantiation, /// there were dependent base classes that could not be searched. void setNotFoundInCurrentInstantiation() { - assert(ResultKind == NotFound && Decls.empty()); + assert((ResultKind == NotFound || + ResultKind == NotFoundInCurrentInstantiation) && + Decls.empty()); ResultKind = NotFoundInCurrentInstantiation; } diff --git a/clang/include/clang/Sema/ParsedAttr.h b/clang/include/clang/Sema/ParsedAttr.h index 25a5fa05b21c7d8ab1054231de0af5f109b74227..8368d9ce61466de8d91bea09956befdd641dc14a 100644 --- a/clang/include/clang/Sema/ParsedAttr.h +++ b/clang/include/clang/Sema/ParsedAttr.h @@ -948,6 +948,7 @@ public: ParsedAttributes(AttributeFactory &factory) : pool(factory) {} ParsedAttributes(const ParsedAttributes &) = delete; ParsedAttributes &operator=(const ParsedAttributes &) = delete; + ParsedAttributes(ParsedAttributes &&G) = default; AttributePool &getPool() const { return pool; } diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index 1ca523ec88c2f9d5e2c3a6ddce57dc0fcb0d6a0a..a80ac6dbc761371e56bcd643d85d147c2d361263 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -4097,12 +4097,12 @@ public: SmallVectorImpl &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI); - /// Add an exception-specification to the given member function - /// (or member function template). The exception-specification was parsed - /// after the method itself was declared. + /// Add an exception-specification to the given member or friend function + /// (or function template). The exception-specification was parsed + /// after the function itself was declared. void actOnDelayedExceptionSpecification( - Decl *Method, ExceptionSpecificationType EST, - SourceRange SpecificationRange, ArrayRef DynamicExceptions, + Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange, + ArrayRef DynamicExceptions, ArrayRef DynamicExceptionRanges, Expr *NoexceptExpr); class InheritedConstructorInfo; @@ -6978,12 +6978,6 @@ public: SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl); - MemberExpr *BuildMemberExpr( - Expr *Base, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec *SS, - SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, - bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, - QualType Ty, ExprValueKind VK, ExprObjectKind OK, - const TemplateArgumentListInfo *TemplateArgs = nullptr); MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, @@ -7472,7 +7466,7 @@ public: bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, CXXScopeSpec &SS); bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, - bool AllowBuiltinCreation = false, + QualType ObjectType, bool AllowBuiltinCreation = false, bool EnteringContext = false); ObjCProtocolDecl *LookupProtocol( IdentifierInfo *II, SourceLocation IdLoc, @@ -8881,11 +8875,13 @@ public: /// functions (but no function templates). FoundFunctions, }; - bool LookupTemplateName( - LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, - bool EnteringContext, bool &MemberOfUnknownSpecialization, - RequiredTemplateKind RequiredTemplate = SourceLocation(), - AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true); + + bool + LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, + QualType ObjectType, bool EnteringContext, + RequiredTemplateKind RequiredTemplate = SourceLocation(), + AssumedTemplateKind *ATK = nullptr, + bool AllowTypoCorrection = true); TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, @@ -9249,7 +9245,8 @@ public: void NoteTemplateParameterLocation(const NamedDecl &Decl); ExprResult BuildExpressionFromDeclTemplateArgument( - const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc); + const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc, + NamedDecl *TemplateParam = nullptr); ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc); @@ -9572,9 +9569,10 @@ public: bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg); - TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, - QualType NTTPType, - SourceLocation Loc); + TemplateArgumentLoc + getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, + SourceLocation Loc, + NamedDecl *TemplateParam = nullptr); /// Get a template argument mapping the given template parameter to itself, /// e.g. for X in \c template, this would return an expression template diff --git a/clang/include/clang/Sema/SemaOpenACC.h b/clang/include/clang/Sema/SemaOpenACC.h index da19503c2902fd270817f049bab819bd574919ce..edb0cbb7c5d5528758478ef89e167387a95164d1 100644 --- a/clang/include/clang/Sema/SemaOpenACC.h +++ b/clang/include/clang/Sema/SemaOpenACC.h @@ -48,8 +48,12 @@ public: SmallVector IntExprs; }; + struct VarListDetails { + SmallVector VarList; + }; + std::variant + IntExprDetails, VarListDetails> Details = std::monostate{}; public: @@ -112,6 +116,16 @@ public: return const_cast(this)->getIntExprs(); } + ArrayRef getVarList() { + assert(ClauseKind == OpenACCClauseKind::Private && + "Parsed clause kind does not have a var-list"); + return std::get(Details).VarList; + } + + ArrayRef getVarList() const { + return const_cast(this)->getVarList(); + } + void setLParenLoc(SourceLocation EndLoc) { LParenLoc = EndLoc; } void setEndLoc(SourceLocation EndLoc) { ClauseRange.setEnd(EndLoc); } @@ -147,7 +161,19 @@ public: ClauseKind == OpenACCClauseKind::NumWorkers || ClauseKind == OpenACCClauseKind::VectorLength) && "Parsed clause kind does not have a int exprs"); - Details = IntExprDetails{IntExprs}; + Details = IntExprDetails{std::move(IntExprs)}; + } + + void setVarListDetails(ArrayRef VarList) { + assert(ClauseKind == OpenACCClauseKind::Private && + "Parsed clause kind does not have a var-list"); + Details = VarListDetails{{VarList.begin(), VarList.end()}}; + } + + void setVarListDetails(llvm::SmallVector &&VarList) { + assert(ClauseKind == OpenACCClauseKind::Private && + "Parsed clause kind does not have a var-list"); + Details = VarListDetails{std::move(VarList)}; } }; @@ -194,6 +220,10 @@ public: ExprResult ActOnIntExpr(OpenACCDirectiveKind DK, OpenACCClauseKind CK, SourceLocation Loc, Expr *IntExpr); + /// Called when encountering a 'var' for OpenACC, ensures it is actually a + /// declaration reference to a variable of the correct type. + ExprResult ActOnVar(Expr *VarExpr); + /// Checks and creates an Array Section used in an OpenACC construct/clause. ExprResult ActOnArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, diff --git a/clang/include/clang/Serialization/ASTRecordReader.h b/clang/include/clang/Serialization/ASTRecordReader.h index 06b80f266a9441639796bea1f55b882fb46d4a0a..1e11d2d5e42f95567b1f2ffbcea5dd056b60dae2 100644 --- a/clang/include/clang/Serialization/ASTRecordReader.h +++ b/clang/include/clang/Serialization/ASTRecordReader.h @@ -269,6 +269,9 @@ public: /// Read an OpenMP children, advancing Idx. void readOMPChildren(OMPChildren *Data); + /// Read a list of Exprs used for a var-list. + llvm::SmallVector readOpenACCVarList(); + /// Read an OpenACC clause, advancing Idx. OpenACCClause *readOpenACCClause(); diff --git a/clang/include/clang/Serialization/ASTRecordWriter.h b/clang/include/clang/Serialization/ASTRecordWriter.h index 1feb8fcbacf772cec2d88a50ee98fcd37241ad36..8b1da49bd4c5760ffec16bae16bd7f1d8576d263 100644 --- a/clang/include/clang/Serialization/ASTRecordWriter.h +++ b/clang/include/clang/Serialization/ASTRecordWriter.h @@ -15,6 +15,7 @@ #define LLVM_CLANG_SERIALIZATION_ASTRECORDWRITER_H #include "clang/AST/AbstractBasicWriter.h" +#include "clang/AST/OpenACCClause.h" #include "clang/AST/OpenMPClause.h" #include "clang/Serialization/ASTWriter.h" #include "clang/Serialization/SourceLocationEncoding.h" @@ -293,6 +294,8 @@ public: /// Writes data related to the OpenMP directives. void writeOMPChildren(OMPChildren *Data); + void writeOpenACCVarList(const OpenACCClauseWithVarList *C); + /// Writes out a single OpenACC Clause. void writeOpenACCClause(const OpenACCClause *C); diff --git a/clang/include/clang/Serialization/ASTWriter.h b/clang/include/clang/Serialization/ASTWriter.h index 6c45b7348b8552c53a21eeff39f52e9f39edd687..a55dfd327670f644b9a3afac476b7d96772278f8 100644 --- a/clang/include/clang/Serialization/ASTWriter.h +++ b/clang/include/clang/Serialization/ASTWriter.h @@ -76,6 +76,10 @@ class StoredDeclsList; class SwitchCase; class Token; +namespace SrcMgr { +class FileInfo; +} // namespace SrcMgr + /// Writes an AST file containing the contents of a translation unit. /// /// The ASTWriter class produces a bitstream containing the serialized @@ -490,6 +494,11 @@ private: /// during \c SourceManager serialization. void computeNonAffectingInputFiles(); + /// Some affecting files can be included from files that are not affecting. + /// This function erases source locations pointing into such files. + SourceLocation getAffectingIncludeLoc(const SourceManager &SourceMgr, + const SrcMgr::FileInfo &File); + /// Returns an adjusted \c FileID, accounting for any non-affecting input /// files. FileID getAdjustedFileID(FileID FID) const; @@ -525,6 +534,7 @@ private: /// Calculate hash of the pcm content. std::pair createSignature() const; + ASTFileSignature createSignatureForNamedModule() const; void WriteInputFiles(SourceManager &SourceMgr, HeaderSearchOptions &HSOpts); void WriteSourceManagerBlock(SourceManager &SourceMgr, @@ -885,6 +895,8 @@ private: /// AST and semantic-analysis consumer that generates a /// precompiled header from the parsed source code. class PCHGenerator : public SemaConsumer { + void anchor() override; + Preprocessor &PP; std::string OutputFile; std::string isysroot; @@ -928,17 +940,34 @@ public: bool hasEmittedPCH() const { return Buffer->IsComplete; } }; -class ReducedBMIGenerator : public PCHGenerator { +class CXX20ModulesGenerator : public PCHGenerator { + void anchor() override; + protected: virtual Module *getEmittingModule(ASTContext &Ctx) override; + CXX20ModulesGenerator(Preprocessor &PP, InMemoryModuleCache &ModuleCache, + StringRef OutputFile, bool GeneratingReducedBMI); + public: - ReducedBMIGenerator(Preprocessor &PP, InMemoryModuleCache &ModuleCache, - StringRef OutputFile); + CXX20ModulesGenerator(Preprocessor &PP, InMemoryModuleCache &ModuleCache, + StringRef OutputFile) + : CXX20ModulesGenerator(PP, ModuleCache, OutputFile, + /*GeneratingReducedBMI=*/false) {} void HandleTranslationUnit(ASTContext &Ctx) override; }; +class ReducedBMIGenerator : public CXX20ModulesGenerator { + void anchor() override; + +public: + ReducedBMIGenerator(Preprocessor &PP, InMemoryModuleCache &ModuleCache, + StringRef OutputFile) + : CXX20ModulesGenerator(PP, ModuleCache, OutputFile, + /*GeneratingReducedBMI=*/true) {} +}; + /// If we can elide the definition of \param D in reduced BMI. /// /// Generally, we can elide the definition of a declaration if it won't affect diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td index 9aa1c6ddfe4492c38f1a07851be9c15587479ccf..520286b57c9fdcbf8e5061e54bc67d0134f201c9 100644 --- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td +++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td @@ -563,6 +563,20 @@ def MismatchedDeallocatorChecker : Checker<"MismatchedDeallocator">, Dependencies<[DynamicMemoryModeling]>, Documentation; +// This must appear before StdCLibraryFunctionsChecker because a dependency. +def StreamChecker : Checker<"Stream">, + HelpText<"Check stream handling functions">, + WeakDependencies<[NonNullParamChecker]>, + CheckerOptions<[ + CmdLineOption + ]>, + Documentation; + def StdCLibraryFunctionsChecker : Checker<"StdCLibraryFunctions">, HelpText<"Check for invalid arguments of C standard library functions, " "and apply relations between arguments and return value">, @@ -581,7 +595,7 @@ def StdCLibraryFunctionsChecker : Checker<"StdCLibraryFunctions">, "true", InAlpha> ]>, - WeakDependencies<[CallAndMessageChecker, NonNullParamChecker]>, + WeakDependencies<[CallAndMessageChecker, NonNullParamChecker, StreamChecker]>, Documentation; def VforkChecker : Checker<"Vfork">, @@ -601,20 +615,6 @@ def PthreadLockChecker : Checker<"PthreadLock">, Dependencies<[PthreadLockBase]>, Documentation; -def StreamChecker : Checker<"Stream">, - HelpText<"Check stream handling functions">, - WeakDependencies<[NonNullParamChecker]>, - CheckerOptions<[ - CmdLineOption - ]>, - Documentation; - def SimpleStreamChecker : Checker<"SimpleStream">, HelpText<"Check for misuses of stream APIs">, Documentation; @@ -1628,6 +1628,7 @@ def TaintTesterChecker : Checker<"TaintTest">, def StreamTesterChecker : Checker<"StreamTester">, HelpText<"Add test functions to StreamChecker for test and debugging " "purposes.">, + WeakDependencies<[StreamChecker]>, Documentation; def ErrnoTesterChecker : Checker<"ErrnoTest">, diff --git a/clang/include/clang/Tooling/CommonOptionsParser.h b/clang/include/clang/Tooling/CommonOptionsParser.h index 3c0480af3779437c51b6b99dd55e52ea96171f1c..5e2cdc6ac458940d509fb78142b5557d19b4949d 100644 --- a/clang/include/clang/Tooling/CommonOptionsParser.h +++ b/clang/include/clang/Tooling/CommonOptionsParser.h @@ -49,17 +49,22 @@ namespace tooling { /// using namespace clang::tooling; /// using namespace llvm; /// -/// static cl::OptionCategory MyToolCategory("My tool options"); +/// static cl::OptionCategory MyToolCategory("my-tool options"); /// static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); /// static cl::extrahelp MoreHelp("\nMore help text...\n"); -/// static cl::opt YourOwnOption(...); -/// ... /// /// int main(int argc, const char **argv) { -/// CommonOptionsParser OptionsParser(argc, argv, MyToolCategory); +/// auto ExpectedParser = +/// CommonOptionsParser::create(argc, argv, MyToolCategory); +/// if (!ExpectedParser) { +/// llvm::errs() << ExpectedParser.takeError(); +/// return 1; +/// } +/// CommonOptionsParser& OptionsParser = ExpectedParser.get(); /// ClangTool Tool(OptionsParser.getCompilations(), /// OptionsParser.getSourcePathList()); -/// return Tool.run(newFrontendActionFactory().get()); +/// return Tool.run( +/// newFrontendActionFactory().get()); /// } /// \endcode class CommonOptionsParser { diff --git a/clang/lib/AST/DeclBase.cpp b/clang/lib/AST/DeclBase.cpp index c33babf8d1df3b2fd9580084ef6eb8c62ca208f2..03e1055251c24f446d502b0bfb2f04d857bf92f0 100644 --- a/clang/lib/AST/DeclBase.cpp +++ b/clang/lib/AST/DeclBase.cpp @@ -1115,7 +1115,9 @@ int64_t Decl::getID() const { const FunctionType *Decl::getFunctionType(bool BlocksToo) const { QualType Ty; - if (const auto *D = dyn_cast(this)) + if (isa(this)) + return nullptr; + else if (const auto *D = dyn_cast(this)) Ty = D->getType(); else if (const auto *D = dyn_cast(this)) Ty = D->getUnderlyingType(); diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp index 63dcdb919c7117f1f727bf6ac020d6f400561af2..ac0b1b38f0162f40303fa574be856e8a04a914b5 100644 --- a/clang/lib/AST/Expr.cpp +++ b/clang/lib/AST/Expr.cpp @@ -103,7 +103,7 @@ const Expr *Expr::skipRValueSubobjectAdjustments( } } else if (const auto *ME = dyn_cast(E)) { if (!ME->isArrow()) { - assert(ME->getBase()->getType()->isRecordType()); + assert(ME->getBase()->getType()->getAsRecordDecl()); if (const auto *Field = dyn_cast(ME->getMemberDecl())) { if (!Field->isBitField() && !Field->getType()->isReferenceType()) { E = ME->getBase(); @@ -3893,9 +3893,14 @@ namespace { } void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { - if (E->getTemporary()->getDestructor()->isTrivial()) { - Inherited::VisitStmt(E); - return; + // Destructor of the temporary might be null if destructor declaration + // is not valid. + if (const CXXDestructorDecl *DtorDecl = + E->getTemporary()->getDestructor()) { + if (DtorDecl->isTrivial()) { + Inherited::VisitStmt(E); + return; + } } NonTrivial = true; diff --git a/clang/lib/AST/ExprClassification.cpp b/clang/lib/AST/ExprClassification.cpp index 2bb8f9aeedc7e245abdf1a2759bd336fc944d87a..390000e3ed383507c651a22aba7961b2d4633654 100644 --- a/clang/lib/AST/ExprClassification.cpp +++ b/clang/lib/AST/ExprClassification.cpp @@ -216,8 +216,13 @@ static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E) { return ClassifyInternal(Ctx, cast(E)->getReplacement()); - case Expr::PackIndexingExprClass: + case Expr::PackIndexingExprClass: { + // A pack-index-expression always expands to an id-expression. + // Consider it as an LValue expression. + if (cast(E)->isInstantiationDependent()) + return Cl::CL_LValue; return ClassifyInternal(Ctx, cast(E)->getSelectedExpr()); + } // C, C++98 [expr.sub]p1: The result is an lvalue of type "T". // C++11 (DR1213): in the case of an array operand, the result is an lvalue diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp index ea3e7304a7423cfee4910724da431de9eab3c84c..f1aa19e4409e159c2a008901306876e615b2f6e3 100644 --- a/clang/lib/AST/ExprConstant.cpp +++ b/clang/lib/AST/ExprConstant.cpp @@ -2706,7 +2706,11 @@ static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, QualType SrcType, QualType DestType, APFloat &Result) { - assert(isa(E) || isa(E)); + assert((isa(E) || isa(E) || + isa(E)) && + "HandleFloatToFloatCast has been checked with only CastExpr, " + "CompoundAssignOperator and ConvertVectorExpr. Please either validate " + "the new expression or address the root cause of this usage."); llvm::RoundingMode RM = getActiveRoundingMode(Info, E); APFloat::opStatus St; APFloat Value = Result; @@ -9237,9 +9241,10 @@ bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid && !Result.IsNullPtr; bool VoidPtrCastMaybeOK = - HasValidResult && - Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), - E->getType()->getPointeeType()); + Result.IsNullPtr || + (HasValidResult && + Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx), + E->getType()->getPointeeType())); // 1. We'll allow it in std::allocator::allocate, and anything which that // calls. // 2. HACK 2022-03-28: Work around an issue with libstdc++'s @@ -10709,8 +10714,11 @@ namespace { bool VisitUnaryImag(const UnaryOperator *E); bool VisitBinaryOperator(const BinaryOperator *E); bool VisitUnaryOperator(const UnaryOperator *E); + bool VisitConvertVectorExpr(const ConvertVectorExpr *E); + bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E); + // FIXME: Missing: conditional operator (for GNU - // conditional select), shufflevector, ExtVectorElementExpr + // conditional select), ExtVectorElementExpr }; } // end anonymous namespace @@ -10961,6 +10969,122 @@ bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { return Success(APValue(ResultElements.data(), ResultElements.size()), E); } +static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO, + const Expr *E, QualType SourceTy, + QualType DestTy, APValue const &Original, + APValue &Result) { + if (SourceTy->isIntegerType()) { + if (DestTy->isRealFloatingType()) { + Result = APValue(APFloat(0.0)); + return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(), + DestTy, Result.getFloat()); + } + if (DestTy->isIntegerType()) { + Result = APValue( + HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt())); + return true; + } + } else if (SourceTy->isRealFloatingType()) { + if (DestTy->isRealFloatingType()) { + Result = Original; + return HandleFloatToFloatCast(Info, E, SourceTy, DestTy, + Result.getFloat()); + } + if (DestTy->isIntegerType()) { + Result = APValue(APSInt()); + return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(), + DestTy, Result.getInt()); + } + } + + Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast) + << SourceTy << DestTy; + return false; +} + +bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) { + APValue Source; + QualType SourceVecType = E->getSrcExpr()->getType(); + if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source)) + return false; + + QualType DestTy = E->getType()->castAs()->getElementType(); + QualType SourceTy = SourceVecType->castAs()->getElementType(); + + const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); + + auto SourceLen = Source.getVectorLength(); + SmallVector ResultElements; + ResultElements.reserve(SourceLen); + for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) { + APValue Elt; + if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy, + Source.getVectorElt(EltNum), Elt)) + return false; + ResultElements.push_back(std::move(Elt)); + } + + return Success(APValue(ResultElements.data(), ResultElements.size()), E); +} + +static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E, + QualType ElemType, APValue const &VecVal1, + APValue const &VecVal2, unsigned EltNum, + APValue &Result) { + unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength(); + unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength(); + + APSInt IndexVal = E->getShuffleMaskIdx(Info.Ctx, EltNum); + int64_t index = IndexVal.getExtValue(); + // The spec says that -1 should be treated as undef for optimizations, + // but in constexpr we'd have to produce an APValue::Indeterminate, + // which is prohibited from being a top-level constant value. Emit a + // diagnostic instead. + if (index == -1) { + Info.FFDiag( + E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr) + << EltNum; + return false; + } + + if (index < 0 || + index >= TotalElementsInInputVector1 + TotalElementsInInputVector2) + llvm_unreachable("Out of bounds shuffle index"); + + if (index >= TotalElementsInInputVector1) + Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1); + else + Result = VecVal1.getVectorElt(index); + return true; +} + +bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) { + APValue VecVal1; + const Expr *Vec1 = E->getExpr(0); + if (!EvaluateAsRValue(Info, Vec1, VecVal1)) + return false; + APValue VecVal2; + const Expr *Vec2 = E->getExpr(1); + if (!EvaluateAsRValue(Info, Vec2, VecVal2)) + return false; + + VectorType const *DestVecTy = E->getType()->castAs(); + QualType DestElTy = DestVecTy->getElementType(); + + auto TotalElementsInOutputVector = DestVecTy->getNumElements(); + + SmallVector ResultElements; + ResultElements.reserve(TotalElementsInOutputVector); + for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) { + APValue Elt; + if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt)) + return false; + ResultElements.push_back(std::move(Elt)); + } + + return Success(APValue(ResultElements.data(), ResultElements.size()), E); +} + //===----------------------------------------------------------------------===// // Array Evaluation //===----------------------------------------------------------------------===// diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp b/clang/lib/AST/Interp/ByteCodeExprGen.cpp index 588ffa55c11e614e0dc4ebb76eafaa234146f3c3..f1a51e81a92c2d2bf5dcb534f4d6f42af7fd9668 100644 --- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp +++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp @@ -212,6 +212,13 @@ bool ByteCodeExprGen::VisitCastExpr(const CastExpr *CE) { if (!this->visit(SubExpr)) return false; + // If SubExpr doesn't result in a pointer, make it one. + if (PrimType FromT = classifyPrim(SubExpr->getType()); FromT != PT_Ptr) { + assert(isPtrType(FromT)); + if (!this->emitDecayPtr(FromT, PT_Ptr, CE)) + return false; + } + PrimType T = classifyPrim(CE->getType()); if (T == PT_IntAP) return this->emitCastPointerIntegralAP(Ctx.getBitWidth(CE->getType()), @@ -924,8 +931,31 @@ bool ByteCodeExprGen::VisitImplicitValueInitExpr(const ImplicitValueIni if (std::optional T = classify(QT)) return this->visitZeroInitializer(*T, QT, E); - if (QT->isRecordType()) - return false; + if (QT->isRecordType()) { + const RecordDecl *RD = QT->getAsRecordDecl(); + assert(RD); + if (RD->isInvalidDecl()) + return false; + if (RD->isUnion()) { + // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the + // object's first non-static named data member is zero-initialized + // FIXME + return false; + } + + if (const auto *CXXRD = dyn_cast(RD); + CXXRD && CXXRD->getNumVBases() > 0) { + // TODO: Diagnose. + return false; + } + + const Record *R = getRecord(QT); + if (!R) + return false; + + assert(Initializing); + return this->visitZeroRecordInitializer(R, E); + } if (QT->isIncompleteArrayType()) return true; @@ -1000,122 +1030,98 @@ bool ByteCodeExprGen::VisitArraySubscriptExpr( template bool ByteCodeExprGen::visitInitList(ArrayRef Inits, + const Expr *ArrayFiller, const Expr *E) { - assert(E->getType()->isRecordType()); - const Record *R = getRecord(E->getType()); + if (E->getType()->isVoidType()) + return this->emitInvalid(E); - if (Inits.size() == 1 && E->getType() == Inits[0]->getType()) { - return this->visitInitializer(Inits[0]); + // Handle discarding first. + if (DiscardResult) { + for (const Expr *Init : Inits) { + if (!this->discard(Init)) + return false; + } + return true; } - unsigned InitIndex = 0; - for (const Expr *Init : Inits) { - // Skip unnamed bitfields. - while (InitIndex < R->getNumFields() && - R->getField(InitIndex)->Decl->isUnnamedBitField()) - ++InitIndex; + // Primitive values. + if (std::optional T = classify(E->getType())) { + assert(!DiscardResult); + if (Inits.size() == 0) + return this->visitZeroInitializer(*T, E->getType(), E); + assert(Inits.size() == 1); + return this->delegate(Inits[0]); + } - if (!this->emitDupPtr(E)) - return false; + QualType T = E->getType(); + if (T->isRecordType()) { + const Record *R = getRecord(E->getType()); - if (std::optional T = classify(Init)) { - const Record::Field *FieldToInit = R->getField(InitIndex); - if (!this->visit(Init)) - return false; + if (Inits.size() == 1 && E->getType() == Inits[0]->getType()) { + return this->visitInitializer(Inits[0]); + } - if (FieldToInit->isBitField()) { - if (!this->emitInitBitField(*T, FieldToInit, E)) - return false; - } else { - if (!this->emitInitField(*T, FieldToInit->Offset, E)) - return false; - } + unsigned InitIndex = 0; + for (const Expr *Init : Inits) { + // Skip unnamed bitfields. + while (InitIndex < R->getNumFields() && + R->getField(InitIndex)->Decl->isUnnamedBitField()) + ++InitIndex; - if (!this->emitPopPtr(E)) + if (!this->emitDupPtr(E)) return false; - ++InitIndex; - } else { - // Initializer for a direct base class. - if (const Record::Base *B = R->getBase(Init->getType())) { - if (!this->emitGetPtrBasePop(B->Offset, Init)) - return false; - - if (!this->visitInitializer(Init)) - return false; - if (!this->emitFinishInitPop(E)) - return false; - // Base initializers don't increase InitIndex, since they don't count - // into the Record's fields. - } else { + if (std::optional T = classify(Init)) { const Record::Field *FieldToInit = R->getField(InitIndex); - // Non-primitive case. Get a pointer to the field-to-initialize - // on the stack and recurse into visitInitializer(). - if (!this->emitGetPtrField(FieldToInit->Offset, Init)) + if (!this->visit(Init)) return false; - if (!this->visitInitializer(Init)) - return false; + if (FieldToInit->isBitField()) { + if (!this->emitInitBitField(*T, FieldToInit, E)) + return false; + } else { + if (!this->emitInitField(*T, FieldToInit->Offset, E)) + return false; + } if (!this->emitPopPtr(E)) return false; ++InitIndex; - } - } - } - return true; -} + } else { + // Initializer for a direct base class. + if (const Record::Base *B = R->getBase(Init->getType())) { + if (!this->emitGetPtrBasePop(B->Offset, Init)) + return false; -/// Pointer to the array(not the element!) must be on the stack when calling -/// this. -template -bool ByteCodeExprGen::visitArrayElemInit(unsigned ElemIndex, - const Expr *Init) { - if (std::optional T = classify(Init->getType())) { - // Visit the primitive element like normal. - if (!this->visit(Init)) - return false; - return this->emitInitElem(*T, ElemIndex, Init); - } + if (!this->visitInitializer(Init)) + return false; - // Advance the pointer currently on the stack to the given - // dimension. - if (!this->emitConstUint32(ElemIndex, Init)) - return false; - if (!this->emitArrayElemPtrUint32(Init)) - return false; - if (!this->visitInitializer(Init)) - return false; - return this->emitFinishInitPop(Init); -} + if (!this->emitFinishInitPop(E)) + return false; + // Base initializers don't increase InitIndex, since they don't count + // into the Record's fields. + } else { + const Record::Field *FieldToInit = R->getField(InitIndex); + // Non-primitive case. Get a pointer to the field-to-initialize + // on the stack and recurse into visitInitializer(). + if (!this->emitGetPtrField(FieldToInit->Offset, Init)) + return false; -template -bool ByteCodeExprGen::VisitInitListExpr(const InitListExpr *E) { - // Handle discarding first. - if (DiscardResult) { - for (const Expr *Init : E->inits()) { - if (!this->discard(Init)) - return false; + if (!this->visitInitializer(Init)) + return false; + + if (!this->emitPopPtr(E)) + return false; + ++InitIndex; + } + } } return true; } - // Primitive values. - if (std::optional T = classify(E->getType())) { - assert(!DiscardResult); - if (E->getNumInits() == 0) - return this->visitZeroInitializer(*T, E->getType(), E); - assert(E->getNumInits() == 1); - return this->delegate(E->inits()[0]); - } - - QualType T = E->getType(); - if (T->isRecordType()) - return this->visitInitList(E->inits(), E); - if (T->isArrayType()) { unsigned ElementIndex = 0; - for (const Expr *Init : E->inits()) { + for (const Expr *Init : Inits) { if (!this->visitArrayElemInit(ElementIndex, Init)) return false; ++ElementIndex; @@ -1123,13 +1129,13 @@ bool ByteCodeExprGen::VisitInitListExpr(const InitListExpr *E) { // Expand the filler expression. // FIXME: This should go away. - if (const Expr *Filler = E->getArrayFiller()) { + if (ArrayFiller) { const ConstantArrayType *CAT = Ctx.getASTContext().getAsConstantArrayType(E->getType()); uint64_t NumElems = CAT->getZExtSize(); for (; ElementIndex != NumElems; ++ElementIndex) { - if (!this->visitArrayElemInit(ElementIndex, Filler)) + if (!this->visitArrayElemInit(ElementIndex, ArrayFiller)) return false; } } @@ -1138,10 +1144,10 @@ bool ByteCodeExprGen::VisitInitListExpr(const InitListExpr *E) { } if (const auto *ComplexTy = E->getType()->getAs()) { - unsigned NumInits = E->getNumInits(); + unsigned NumInits = Inits.size(); if (NumInits == 1) - return this->delegate(E->inits()[0]); + return this->delegate(Inits[0]); QualType ElemQT = ComplexTy->getElementType(); PrimType ElemT = classifyPrim(ElemQT); @@ -1155,7 +1161,7 @@ bool ByteCodeExprGen::VisitInitListExpr(const InitListExpr *E) { } } else if (NumInits == 2) { unsigned InitIndex = 0; - for (const Expr *Init : E->inits()) { + for (const Expr *Init : Inits) { if (!this->visit(Init)) return false; @@ -1169,22 +1175,32 @@ bool ByteCodeExprGen::VisitInitListExpr(const InitListExpr *E) { if (const auto *VecT = E->getType()->getAs()) { unsigned NumVecElements = VecT->getNumElements(); - assert(NumVecElements >= E->getNumInits()); + assert(NumVecElements >= Inits.size()); QualType ElemQT = VecT->getElementType(); PrimType ElemT = classifyPrim(ElemQT); // All initializer elements. unsigned InitIndex = 0; - for (const Expr *Init : E->inits()) { + for (const Expr *Init : Inits) { if (!this->visit(Init)) return false; - if (!this->emitInitElem(ElemT, InitIndex, E)) - return false; - ++InitIndex; + // If the initializer is of vector type itself, we have to deconstruct + // that and initialize all the target fields from the initializer fields. + if (const auto *InitVecT = Init->getType()->getAs()) { + if (!this->emitCopyArray(ElemT, 0, InitIndex, InitVecT->getNumElements(), E)) + return false; + InitIndex += InitVecT->getNumElements(); + } else { + if (!this->emitInitElem(ElemT, InitIndex, E)) + return false; + ++InitIndex; + } } + assert(InitIndex <= NumVecElements); + // Fill the rest with zeroes. for (; InitIndex != NumVecElements; ++InitIndex) { if (!this->visitZeroInitializer(ElemT, ElemQT, E)) @@ -1198,19 +1214,38 @@ bool ByteCodeExprGen::VisitInitListExpr(const InitListExpr *E) { return false; } +/// Pointer to the array(not the element!) must be on the stack when calling +/// this. template -bool ByteCodeExprGen::VisitCXXParenListInitExpr( - const CXXParenListInitExpr *E) { - if (DiscardResult) { - for (const Expr *Init : E->getInitExprs()) { - if (!this->discard(Init)) - return false; - } - return true; +bool ByteCodeExprGen::visitArrayElemInit(unsigned ElemIndex, + const Expr *Init) { + if (std::optional T = classify(Init->getType())) { + // Visit the primitive element like normal. + if (!this->visit(Init)) + return false; + return this->emitInitElem(*T, ElemIndex, Init); } - assert(E->getType()->isRecordType()); - return this->visitInitList(E->getInitExprs(), E); + // Advance the pointer currently on the stack to the given + // dimension. + if (!this->emitConstUint32(ElemIndex, Init)) + return false; + if (!this->emitArrayElemPtrUint32(Init)) + return false; + if (!this->visitInitializer(Init)) + return false; + return this->emitFinishInitPop(Init); +} + +template +bool ByteCodeExprGen::VisitInitListExpr(const InitListExpr *E) { + return this->visitInitList(E->inits(), E->getArrayFiller(), E); +} + +template +bool ByteCodeExprGen::VisitCXXParenListInitExpr( + const CXXParenListInitExpr *E) { + return this->visitInitList(E->getInitExprs(), E->getArrayFiller(), E); } template @@ -1333,6 +1368,20 @@ bool ByteCodeExprGen::VisitUnaryExprOrTypeTraitExpr( assert(E->getTypeOfArgument()->isSizelessVectorType()); } + if (Kind == UETT_VecStep) { + if (const auto *VT = E->getTypeOfArgument()->getAs()) { + unsigned N = VT->getNumElements(); + + // The vec_step built-in functions that take a 3-component + // vector return 4. (OpenCL 1.1 spec 6.11.12) + if (N == 3) + N = 4; + + return this->emitConst(N, E); + } + return this->emitConst(1, E); + } + return false; } @@ -2243,26 +2292,54 @@ bool ByteCodeExprGen::VisitCXXScalarValueInitExpr( if (std::optional T = classify(Ty)) return this->visitZeroInitializer(*T, Ty, E); - assert(Ty->isAnyComplexType()); - if (!Initializing) { - std::optional LocalIndex = allocateLocal(E, /*IsExtended=*/false); - if (!LocalIndex) - return false; - if (!this->emitGetPtrLocal(*LocalIndex, E)) - return false; + if (const auto *CT = Ty->getAs()) { + if (!Initializing) { + std::optional LocalIndex = + allocateLocal(E, /*IsExtended=*/false); + if (!LocalIndex) + return false; + if (!this->emitGetPtrLocal(*LocalIndex, E)) + return false; + } + + // Initialize both fields to 0. + QualType ElemQT = CT->getElementType(); + PrimType ElemT = classifyPrim(ElemQT); + + for (unsigned I = 0; I != 2; ++I) { + if (!this->visitZeroInitializer(ElemT, ElemQT, E)) + return false; + if (!this->emitInitElem(ElemT, I, E)) + return false; + } + return true; } - // Initialize both fields to 0. - QualType ElemQT = Ty->getAs()->getElementType(); - PrimType ElemT = classifyPrim(ElemQT); + if (const auto *VT = Ty->getAs()) { + // FIXME: Code duplication with the _Complex case above. + if (!Initializing) { + std::optional LocalIndex = + allocateLocal(E, /*IsExtended=*/false); + if (!LocalIndex) + return false; + if (!this->emitGetPtrLocal(*LocalIndex, E)) + return false; + } - for (unsigned I = 0; I != 2; ++I) { - if (!this->visitZeroInitializer(ElemT, ElemQT, E)) - return false; - if (!this->emitInitElem(ElemT, I, E)) - return false; + // Initialize all fields to 0. + QualType ElemQT = VT->getElementType(); + PrimType ElemT = classifyPrim(ElemQT); + + for (unsigned I = 0, N = VT->getNumElements(); I != N; ++I) { + if (!this->visitZeroInitializer(ElemT, ElemQT, E)) + return false; + if (!this->emitInitElem(ElemT, I, E)) + return false; + } + return true; } - return true; + + return false; } template @@ -2340,8 +2417,7 @@ bool ByteCodeExprGen::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { if (!this->emitGetPtrGlobal(*GlobalIndex, E)) return false; - const Record *R = this->getRecord(E->getType()); - assert(R); + assert(this->getRecord(E->getType())); const APValue &V = E->getGuidDecl()->getAsAPValue(); if (V.getKind() == APValue::None) @@ -2349,41 +2425,8 @@ bool ByteCodeExprGen::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { assert(V.isStruct()); assert(V.getStructNumBases() == 0); - // FIXME: This could be useful in visitAPValue, too. - for (unsigned I = 0, N = V.getStructNumFields(); I != N; ++I) { - const APValue &F = V.getStructField(I); - const Record::Field *RF = R->getField(I); - - if (F.isInt()) { - PrimType T = classifyPrim(RF->Decl->getType()); - if (!this->visitAPValue(F, T, E)) - return false; - if (!this->emitInitField(T, RF->Offset, E)) - return false; - } else if (F.isArray()) { - assert(RF->Desc->isPrimitiveArray()); - const auto *ArrType = RF->Decl->getType()->getAsArrayTypeUnsafe(); - PrimType ElemT = classifyPrim(ArrType->getElementType()); - assert(ArrType); - - if (!this->emitDupPtr(E)) - return false; - if (!this->emitGetPtrField(RF->Offset, E)) - return false; - - for (unsigned A = 0, AN = F.getArraySize(); A != AN; ++A) { - if (!this->visitAPValue(F.getArrayInitializedElt(A), ElemT, E)) - return false; - if (!this->emitInitElem(ElemT, A, E)) - return false; - } - - if (!this->emitPopPtr(E)) - return false; - } else { - assert(false && "I don't think this should be possible"); - } - } + if (!this->visitAPValueInitializer(V, E)) + return false; return this->emitFinishInit(E); } @@ -2948,6 +2991,54 @@ bool ByteCodeExprGen::visitAPValue(const APValue &Val, return false; } +template +bool ByteCodeExprGen::visitAPValueInitializer(const APValue &Val, + const Expr *E) { + if (Val.isStruct()) { + const Record *R = this->getRecord(E->getType()); + assert(R); + + for (unsigned I = 0, N = Val.getStructNumFields(); I != N; ++I) { + const APValue &F = Val.getStructField(I); + const Record::Field *RF = R->getField(I); + + if (F.isInt()) { + PrimType T = classifyPrim(RF->Decl->getType()); + if (!this->visitAPValue(F, T, E)) + return false; + if (!this->emitInitField(T, RF->Offset, E)) + return false; + } else if (F.isArray()) { + assert(RF->Desc->isPrimitiveArray()); + const auto *ArrType = RF->Decl->getType()->getAsArrayTypeUnsafe(); + PrimType ElemT = classifyPrim(ArrType->getElementType()); + assert(ArrType); + + if (!this->emitDupPtr(E)) + return false; + if (!this->emitGetPtrField(RF->Offset, E)) + return false; + + for (unsigned A = 0, AN = F.getArraySize(); A != AN; ++A) { + if (!this->visitAPValue(F.getArrayInitializedElt(A), ElemT, E)) + return false; + if (!this->emitInitElem(ElemT, A, E)) + return false; + } + + if (!this->emitPopPtr(E)) + return false; + } else { + assert(false && "I don't think this should be possible"); + } + } + return true; + } + // TODO: Other types. + + return false; +} + template bool ByteCodeExprGen::VisitBuiltinCallExpr(const CallExpr *E) { const Function *Func = getFunction(E->getDirectCallee()); @@ -3469,9 +3560,17 @@ bool ByteCodeExprGen::VisitDeclRefExpr(const DeclRefExpr *E) { } else if (const auto *FuncDecl = dyn_cast(D)) { const Function *F = getFunction(FuncDecl); return F && this->emitGetFnPtr(F, E); - } else if (isa(D)) { - if (std::optional Index = P.getOrCreateGlobal(D)) - return this->emitGetPtrGlobal(*Index, E); + } else if (const auto *TPOD = dyn_cast(D)) { + if (std::optional Index = P.getOrCreateGlobal(D)) { + if (!this->emitGetPtrGlobal(*Index, E)) + return false; + if (std::optional T = classify(E->getType())) { + if (!this->visitAPValue(TPOD->getValue(), *T, E)) + return false; + return this->emitInitGlobal(*T, *Index, E); + } + return this->visitAPValueInitializer(TPOD->getValue(), E); + } return false; } diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.h b/clang/lib/AST/Interp/ByteCodeExprGen.h index 4a57f76ae5b3729a7ec81e9b2f7665c2c09b76c1..a89e37c67aa67c16876b795bd481fc665391012d 100644 --- a/clang/lib/AST/Interp/ByteCodeExprGen.h +++ b/clang/lib/AST/Interp/ByteCodeExprGen.h @@ -181,6 +181,7 @@ protected: bool visitVarDecl(const VarDecl *VD); /// Visit an APValue. bool visitAPValue(const APValue &Val, PrimType ValType, const Expr *E); + bool visitAPValueInitializer(const APValue &Val, const Expr *E); /// Visits an expression and converts it to a boolean. bool visitBool(const Expr *E); @@ -224,7 +225,8 @@ protected: return this->emitFinishInitPop(I); } - bool visitInitList(ArrayRef Inits, const Expr *E); + bool visitInitList(ArrayRef Inits, const Expr *ArrayFiller, + const Expr *E); bool visitArrayElemInit(unsigned ElemIndex, const Expr *Init); /// Creates a local primitive value. diff --git a/clang/lib/AST/Interp/ByteCodeStmtGen.cpp b/clang/lib/AST/Interp/ByteCodeStmtGen.cpp index ec2fe39a8aeae9faeca70bdae4a74b936571b49f..ff92bc117f9efb4082701089bb29b7cb4e10361d 100644 --- a/clang/lib/AST/Interp/ByteCodeStmtGen.cpp +++ b/clang/lib/AST/Interp/ByteCodeStmtGen.cpp @@ -292,8 +292,9 @@ bool ByteCodeStmtGen::visitStmt(const Stmt *S) { case Stmt::GCCAsmStmtClass: case Stmt::MSAsmStmtClass: case Stmt::GotoStmtClass: - case Stmt::LabelStmtClass: return this->emitInvalid(S); + case Stmt::LabelStmtClass: + return this->visitStmt(cast(S)->getSubStmt()); default: { if (auto *Exp = dyn_cast(S)) return this->discard(Exp); @@ -332,7 +333,8 @@ bool ByteCodeStmtGen::visitCompoundStmt( template bool ByteCodeStmtGen::visitDeclStmt(const DeclStmt *DS) { for (auto *D : DS->decls()) { - if (isa(D)) + if (isa(D)) continue; const auto *VD = dyn_cast(D); diff --git a/clang/lib/AST/Interp/Disasm.cpp b/clang/lib/AST/Interp/Disasm.cpp index 01cc88ea9a84593d0262cded21569169d5ebbce1..ccdc96a79436dad25bcf595c537e7953b64fe042 100644 --- a/clang/lib/AST/Interp/Disasm.cpp +++ b/clang/lib/AST/Interp/Disasm.cpp @@ -200,7 +200,7 @@ LLVM_DUMP_METHOD void Descriptor::dump(llvm::raw_ostream &OS) const { OS << " primitive"; if (isZeroSizeArray()) - OS << " zero-size-arrary"; + OS << " zero-size-array"; else if (isUnknownSizeArray()) OS << " unknown-size-array"; diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h index 9da0286deada175870c5174c940751af41b3d7f8..66d30cc3fbaabac59bbb3335a95e13a4056d56ae 100644 --- a/clang/lib/AST/Interp/Interp.h +++ b/clang/lib/AST/Interp/Interp.h @@ -1935,10 +1935,15 @@ template inline bool Shr(InterpState &S, CodePtr OpPC) { using LT = typename PrimConv::T; using RT = typename PrimConv::T; - const auto &RHS = S.Stk.pop(); + auto RHS = S.Stk.pop(); const auto &LHS = S.Stk.pop(); const unsigned Bits = LHS.bitWidth(); + // OpenCL 6.3j: shift values are effectively % word size of LHS. + if (S.getLangOpts().OpenCL) + RT::bitAnd(RHS, RT::from(LHS.bitWidth() - 1, RHS.bitWidth()), + RHS.bitWidth(), &RHS); + if (!CheckShift(S, OpPC, LHS, RHS, Bits)) return false; @@ -1960,10 +1965,15 @@ template inline bool Shl(InterpState &S, CodePtr OpPC) { using LT = typename PrimConv::T; using RT = typename PrimConv::T; - const auto &RHS = S.Stk.pop(); + auto RHS = S.Stk.pop(); const auto &LHS = S.Stk.pop(); const unsigned Bits = LHS.bitWidth(); + // OpenCL 6.3j: shift values are effectively % word size of LHS. + if (S.getLangOpts().OpenCL) + RT::bitAnd(RHS, RT::from(LHS.bitWidth() - 1, RHS.bitWidth()), + RHS.bitWidth(), &RHS); + if (!CheckShift(S, OpPC, LHS, RHS, Bits)) return false; @@ -2080,6 +2090,24 @@ inline bool ArrayElemPop(InterpState &S, CodePtr OpPC, uint32_t Index) { return true; } +template ::T> +inline bool CopyArray(InterpState &S, CodePtr OpPC, uint32_t SrcIndex, uint32_t DestIndex, uint32_t Size) { + const auto &SrcPtr = S.Stk.pop(); + const auto &DestPtr = S.Stk.peek(); + + for (uint32_t I = 0; I != Size; ++I) { + const Pointer &SP = SrcPtr.atIndex(SrcIndex + I); + + if (!CheckLoad(S, OpPC, SP)) + return false; + + const Pointer &DP = DestPtr.atIndex(DestIndex + I); + DP.deref() = SP.deref(); + DP.initialize(); + } + return true; +} + /// Just takes a pointer and checks if it's an incomplete /// array type. inline bool ArrayDecay(InterpState &S, CodePtr OpPC) { diff --git a/clang/lib/AST/Interp/Opcodes.td b/clang/lib/AST/Interp/Opcodes.td index 2a97b978b523251fa64c91c77310b5224681596b..cfbd7f93c32de83552dc5973d3c9076345ac2cac 100644 --- a/clang/lib/AST/Interp/Opcodes.td +++ b/clang/lib/AST/Interp/Opcodes.td @@ -376,7 +376,11 @@ def ArrayElem : Opcode { let HasGroup = 1; } - +def CopyArray : Opcode { + let Args = [ArgUint32, ArgUint32, ArgUint32]; + let Types = [AllTypeClass]; + let HasGroup = 1; +} //===----------------------------------------------------------------------===// // Direct field accessors diff --git a/clang/lib/AST/Interp/Program.cpp b/clang/lib/AST/Interp/Program.cpp index 3773e0662f784ce3b9f23224ee5150f5c1caaf73..02075c20cf556ddebcb69a3897b47129af928104 100644 --- a/clang/lib/AST/Interp/Program.cpp +++ b/clang/lib/AST/Interp/Program.cpp @@ -173,7 +173,8 @@ std::optional Program::createGlobal(const ValueDecl *VD, if (const auto *Var = dyn_cast(VD)) { IsStatic = Context::shouldBeGloballyIndexed(VD); IsExtern = Var->hasExternalStorage(); - } else if (isa(VD)) { + } else if (isa(VD)) { IsStatic = true; IsExtern = false; } else { diff --git a/clang/lib/AST/OpenACCClause.cpp b/clang/lib/AST/OpenACCClause.cpp index 6cd5b28802187de369e264ecb50f610fc16d98bc..885f3b7618ec55b2f597c8598f878442d3edca16 100644 --- a/clang/lib/AST/OpenACCClause.cpp +++ b/clang/lib/AST/OpenACCClause.cpp @@ -134,35 +134,67 @@ OpenACCNumGangsClause *OpenACCNumGangsClause::Create(const ASTContext &C, return new (Mem) OpenACCNumGangsClause(BeginLoc, LParenLoc, IntExprs, EndLoc); } +OpenACCPrivateClause *OpenACCPrivateClause::Create(const ASTContext &C, + SourceLocation BeginLoc, + SourceLocation LParenLoc, + ArrayRef VarList, + SourceLocation EndLoc) { + void *Mem = C.Allocate( + OpenACCPrivateClause::totalSizeToAlloc(VarList.size())); + return new (Mem) OpenACCPrivateClause(BeginLoc, LParenLoc, VarList, EndLoc); +} + //===----------------------------------------------------------------------===// // OpenACC clauses printing methods //===----------------------------------------------------------------------===// + +void OpenACCClausePrinter::printExpr(const Expr *E) { + E->printPretty(OS, nullptr, Policy, 0); +} + void OpenACCClausePrinter::VisitDefaultClause(const OpenACCDefaultClause &C) { OS << "default(" << C.getDefaultClauseKind() << ")"; } void OpenACCClausePrinter::VisitIfClause(const OpenACCIfClause &C) { - OS << "if(" << C.getConditionExpr() << ")"; + OS << "if("; + printExpr(C.getConditionExpr()); + OS << ")"; } void OpenACCClausePrinter::VisitSelfClause(const OpenACCSelfClause &C) { OS << "self"; - if (const Expr *CondExpr = C.getConditionExpr()) - OS << "(" << CondExpr << ")"; + if (const Expr *CondExpr = C.getConditionExpr()) { + OS << "("; + printExpr(CondExpr); + OS << ")"; + } } void OpenACCClausePrinter::VisitNumGangsClause(const OpenACCNumGangsClause &C) { OS << "num_gangs("; - llvm::interleaveComma(C.getIntExprs(), OS); + llvm::interleaveComma(C.getIntExprs(), OS, + [&](const Expr *E) { printExpr(E); }); OS << ")"; } void OpenACCClausePrinter::VisitNumWorkersClause( const OpenACCNumWorkersClause &C) { - OS << "num_workers(" << C.getIntExpr() << ")"; + OS << "num_workers("; + printExpr(C.getIntExpr()); + OS << ")"; } void OpenACCClausePrinter::VisitVectorLengthClause( const OpenACCVectorLengthClause &C) { - OS << "vector_length(" << C.getIntExpr() << ")"; + OS << "vector_length("; + printExpr(C.getIntExpr()); + OS << ")"; +} + +void OpenACCClausePrinter::VisitPrivateClause(const OpenACCPrivateClause &C) { + OS << "private("; + llvm::interleaveComma(C.getVarList(), OS, + [&](const Expr *E) { printExpr(E); }); + OS << ")"; } diff --git a/clang/lib/AST/StmtPrinter.cpp b/clang/lib/AST/StmtPrinter.cpp index f010d36513a49e34bf6e7f4295bbb05a7bfb3577..be2d5a2eb6b46d1bf63df77bbdc7dd2cdd085fe5 100644 --- a/clang/lib/AST/StmtPrinter.cpp +++ b/clang/lib/AST/StmtPrinter.cpp @@ -1148,9 +1148,10 @@ void StmtPrinter::VisitOpenACCComputeConstruct(OpenACCComputeConstruct *S) { if (!S->clauses().empty()) { OS << ' '; - OpenACCClausePrinter Printer(OS); + OpenACCClausePrinter Printer(OS, Policy); Printer.VisitClauseList(S->clauses()); } + OS << '\n'; PrintStmt(S->getStructuredBlock()); } diff --git a/clang/lib/AST/StmtProfile.cpp b/clang/lib/AST/StmtProfile.cpp index a95f5c6103e24dd49332611b32a44650fae7e303..973f6f97bae0bf4e484e254ca80cb29e863dfecc 100644 --- a/clang/lib/AST/StmtProfile.cpp +++ b/clang/lib/AST/StmtProfile.cpp @@ -2509,6 +2509,12 @@ void OpenACCClauseProfiler::VisitNumWorkersClause( Profiler.VisitStmt(Clause.getIntExpr()); } +void OpenACCClauseProfiler::VisitPrivateClause( + const OpenACCPrivateClause &Clause) { + for (auto *E : Clause.getVarList()) + Profiler.VisitStmt(E); +} + void OpenACCClauseProfiler::VisitVectorLengthClause( const OpenACCVectorLengthClause &Clause) { assert(Clause.hasIntExpr() && diff --git a/clang/lib/AST/TextNodeDumper.cpp b/clang/lib/AST/TextNodeDumper.cpp index 8f0a9a9b0ed0bcd0659571935f450e59737b401e..89f50d6dacfd23b512eac7b06844fd2d62e79a39 100644 --- a/clang/lib/AST/TextNodeDumper.cpp +++ b/clang/lib/AST/TextNodeDumper.cpp @@ -401,6 +401,7 @@ void TextNodeDumper::Visit(const OpenACCClause *C) { case OpenACCClauseKind::Self: case OpenACCClauseKind::NumGangs: case OpenACCClauseKind::NumWorkers: + case OpenACCClauseKind::Private: case OpenACCClauseKind::VectorLength: // The condition expression will be printed as a part of the 'children', // but print 'clause' here so it is clear what is happening from the dump. diff --git a/clang/lib/AST/Type.cpp b/clang/lib/AST/Type.cpp index 8aaa6801d85b8b89cb81616de1fd754d8ec71eb7..68e81f45b4c28eeab60a390a73f654dc8f9a7e46 100644 --- a/clang/lib/AST/Type.cpp +++ b/clang/lib/AST/Type.cpp @@ -2510,6 +2510,18 @@ bool Type::isSveVLSBuiltinType() const { return false; } +QualType Type::getSizelessVectorEltType(const ASTContext &Ctx) const { + assert(isSizelessVectorType() && "Must be sizeless vector type"); + // Currently supports SVE and RVV + if (isSVESizelessBuiltinType()) + return getSveEltType(Ctx); + + if (isRVVSizelessBuiltinType()) + return getRVVEltType(Ctx); + + llvm_unreachable("Unhandled type"); +} + QualType Type::getSveEltType(const ASTContext &Ctx) const { assert(isSveVLSBuiltinType() && "unsupported type!"); diff --git a/clang/lib/Analysis/ExprMutationAnalyzer.cpp b/clang/lib/Analysis/ExprMutationAnalyzer.cpp index 941322be8f870bc06d50418e971c47f8d09d6531..3b3782fa1db9a0547e40ced1dc135774f5c15e5b 100644 --- a/clang/lib/Analysis/ExprMutationAnalyzer.cpp +++ b/clang/lib/Analysis/ExprMutationAnalyzer.cpp @@ -235,15 +235,17 @@ const Stmt *ExprMutationAnalyzer::Analyzer::findMutationMemoized( if (Memoized != MemoizedResults.end()) return Memoized->second; + // Assume Exp is not mutated before analyzing Exp. + MemoizedResults[Exp] = nullptr; if (isUnevaluated(Exp)) - return MemoizedResults[Exp] = nullptr; + return nullptr; for (const auto &Finder : Finders) { if (const Stmt *S = (this->*Finder)(Exp)) return MemoizedResults[Exp] = S; } - return MemoizedResults[Exp] = nullptr; + return nullptr; } const Stmt * diff --git a/clang/lib/Basic/CMakeLists.txt b/clang/lib/Basic/CMakeLists.txt index 2e218ba7c84ccabf6bf055c96586a07a5c10ceb8..824d4a0e2eee57732132b0c33a61876113ca74a5 100644 --- a/clang/lib/Basic/CMakeLists.txt +++ b/clang/lib/Basic/CMakeLists.txt @@ -130,6 +130,9 @@ add_clang_library(clangBasic DEPENDS omp_gen ClangDriverOptions + # These generated headers are included transitively. + ARMTargetParserTableGen + AArch64TargetParserTableGen ) target_link_libraries(clangBasic diff --git a/clang/lib/Basic/Targets/WebAssembly.cpp b/clang/lib/Basic/Targets/WebAssembly.cpp index d473fd19086460ba508499e5bddad840a789912f..a6d820e108088f9b3259dcd1884f57a27fd679fe 100644 --- a/clang/lib/Basic/Targets/WebAssembly.cpp +++ b/clang/lib/Basic/Targets/WebAssembly.cpp @@ -47,6 +47,7 @@ bool WebAssemblyTargetInfo::hasFeature(StringRef Feature) const { return llvm::StringSwitch(Feature) .Case("simd128", SIMDLevel >= SIMD128) .Case("relaxed-simd", SIMDLevel >= RelaxedSIMD) + .Case("half-precision", HasHalfPrecision) .Case("nontrapping-fptoint", HasNontrappingFPToInt) .Case("sign-ext", HasSignExt) .Case("exception-handling", HasExceptionHandling) @@ -99,6 +100,8 @@ void WebAssemblyTargetInfo::getTargetDefines(const LangOptions &Opts, Builder.defineMacro("__wasm_extended_const__"); if (HasMultiMemory) Builder.defineMacro("__wasm_multimemory__"); + if (HasHalfPrecision) + Builder.defineMacro("__wasm_half_precision__"); Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1"); Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2"); @@ -147,19 +150,26 @@ void WebAssemblyTargetInfo::setFeatureEnabled(llvm::StringMap &Features, bool WebAssemblyTargetInfo::initFeatureMap( llvm::StringMap &Features, DiagnosticsEngine &Diags, StringRef CPU, const std::vector &FeaturesVec) const { - if (CPU == "bleeding-edge") { + auto addGenericFeatures = [&]() { + Features["multivalue"] = true; + Features["mutable-globals"] = true; + Features["sign-ext"] = true; + }; + auto addBleedingEdgeFeatures = [&]() { + addGenericFeatures(); Features["atomics"] = true; Features["bulk-memory"] = true; Features["multimemory"] = true; - Features["mutable-globals"] = true; Features["nontrapping-fptoint"] = true; Features["reference-types"] = true; - Features["sign-ext"] = true; Features["tail-call"] = true; + Features["half-precision"] = true; setSIMDLevel(Features, SIMD128, true); - } else if (CPU == "generic") { - Features["mutable-globals"] = true; - Features["sign-ext"] = true; + }; + if (CPU == "generic") { + addGenericFeatures(); + } else if (CPU == "bleeding-edge") { + addBleedingEdgeFeatures(); } return TargetInfo::initFeatureMap(Features, Diags, CPU, FeaturesVec); @@ -216,6 +226,15 @@ bool WebAssemblyTargetInfo::handleTargetFeatures( HasBulkMemory = false; continue; } + if (Feature == "+half-precision") { + SIMDLevel = std::max(SIMDLevel, SIMD128); + HasHalfPrecision = true; + continue; + } + if (Feature == "-half-precision") { + HasHalfPrecision = false; + continue; + } if (Feature == "+atomics") { HasAtomics = true; continue; diff --git a/clang/lib/Basic/Targets/WebAssembly.h b/clang/lib/Basic/Targets/WebAssembly.h index 5568aa28eaefa7152637b70f4343937676f2a3d4..e4c18879182ed73f45aa0370c97155bc410aa151 100644 --- a/clang/lib/Basic/Targets/WebAssembly.h +++ b/clang/lib/Basic/Targets/WebAssembly.h @@ -64,6 +64,7 @@ class LLVM_LIBRARY_VISIBILITY WebAssemblyTargetInfo : public TargetInfo { bool HasReferenceTypes = false; bool HasExtendedConst = false; bool HasMultiMemory = false; + bool HasHalfPrecision = false; std::string ABI; diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp index d08ab5391489142031d839bd230bfe23023cdd8e..a370734e00d3e1cb4dc147d927695d66d279c6f4 100644 --- a/clang/lib/CodeGen/CGBuiltin.cpp +++ b/clang/lib/CodeGen/CGBuiltin.cpp @@ -3885,9 +3885,12 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, } case Builtin::BI__builtin_reduce_max: { - auto GetIntrinsicID = [](QualType QT) { + auto GetIntrinsicID = [this](QualType QT) { if (auto *VecTy = QT->getAs()) QT = VecTy->getElementType(); + else if (QT->isSizelessVectorType()) + QT = QT->getSizelessVectorEltType(CGM.getContext()); + if (QT->isSignedIntegerType()) return llvm::Intrinsic::vector_reduce_smax; if (QT->isUnsignedIntegerType()) @@ -3900,9 +3903,12 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, } case Builtin::BI__builtin_reduce_min: { - auto GetIntrinsicID = [](QualType QT) { + auto GetIntrinsicID = [this](QualType QT) { if (auto *VecTy = QT->getAs()) QT = VecTy->getElementType(); + else if (QT->isSizelessVectorType()) + QT = QT->getSizelessVectorEltType(CGM.getContext()); + if (QT->isSignedIntegerType()) return llvm::Intrinsic::vector_reduce_smin; if (QT->isUnsignedIntegerType()) diff --git a/clang/lib/CodeGen/CGCUDANV.cpp b/clang/lib/CodeGen/CGCUDANV.cpp index 370642cb3d5364f8622125c6298d00fc61f7194c..670bc4bf72cecb906ca912164cdfc79307ef9e8f 100644 --- a/clang/lib/CodeGen/CGCUDANV.cpp +++ b/clang/lib/CodeGen/CGCUDANV.cpp @@ -424,6 +424,33 @@ void CGNVCUDARuntime::emitDeviceStubBodyNew(CodeGenFunction &CGF, CGM.CreateRuntimeFunction(FTy, LaunchKernelName); CGF.EmitCall(FI, CGCallee::forDirect(cudaLaunchKernelFn), ReturnValueSlot(), LaunchKernelArgs); + + // To prevent CUDA device stub functions from being merged by ICF in MSVC + // environment, create an unique global variable for each kernel and write to + // the variable in the device stub. + if (CGM.getContext().getTargetInfo().getCXXABI().isMicrosoft() && + !CGF.getLangOpts().HIP) { + llvm::Function *KernelFunction = llvm::cast(Kernel); + std::string GlobalVarName = (KernelFunction->getName() + ".id").str(); + + llvm::GlobalVariable *HandleVar = + CGM.getModule().getNamedGlobal(GlobalVarName); + if (!HandleVar) { + HandleVar = new llvm::GlobalVariable( + CGM.getModule(), CGM.Int8Ty, + /*Constant=*/false, KernelFunction->getLinkage(), + llvm::ConstantInt::get(CGM.Int8Ty, 0), GlobalVarName); + HandleVar->setDSOLocal(KernelFunction->isDSOLocal()); + HandleVar->setVisibility(KernelFunction->getVisibility()); + if (KernelFunction->hasComdat()) + HandleVar->setComdat(CGM.getModule().getOrInsertComdat(GlobalVarName)); + } + + CGF.Builder.CreateAlignedStore(llvm::ConstantInt::get(CGM.Int8Ty, 1), + HandleVar, CharUnits::One(), + /*IsVolatile=*/true); + } + CGF.EmitBranch(EndBlock); CGF.EmitBlock(EndBlock); diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp index d2d92140b6b2a33e6376c265051b065f0e59f8c2..69548902dc43b9b756e0ad54735fcac5ce40c581 100644 --- a/clang/lib/CodeGen/CGCall.cpp +++ b/clang/lib/CodeGen/CGCall.cpp @@ -4698,11 +4698,11 @@ void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E, AggValueSlot Slot = args.isUsingInAlloca() ? createPlaceholderSlot(*this, type) : CreateAggTemp(type, "agg.tmp"); - bool DestroyedInCallee = true, NeedsEHCleanup = true; + bool DestroyedInCallee = true, NeedsCleanup = true; if (const auto *RD = type->getAsCXXRecordDecl()) DestroyedInCallee = RD->hasNonTrivialDestructor(); else - NeedsEHCleanup = needsEHCleanup(type.isDestructedType()); + NeedsCleanup = type.isDestructedType(); if (DestroyedInCallee) Slot.setExternallyDestructed(); @@ -4711,14 +4711,15 @@ void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E, RValue RV = Slot.asRValue(); args.add(RV, type); - if (DestroyedInCallee && NeedsEHCleanup) { + if (DestroyedInCallee && NeedsCleanup) { // Create a no-op GEP between the placeholder and the cleanup so we can // RAUW it successfully. It also serves as a marker of the first // instruction where the cleanup is active. - pushFullExprCleanup(EHCleanup, Slot.getAddress(), - type); + pushFullExprCleanup(NormalAndEHCleanup, + Slot.getAddress(), type); // This unreachable is a temporary marker which will be removed later. - llvm::Instruction *IsActive = Builder.CreateUnreachable(); + llvm::Instruction *IsActive = + Builder.CreateFlagLoad(llvm::Constant::getNullValue(Int8PtrTy)); args.addArgCleanupDeactivation(EHStack.stable_begin(), IsActive); } return; diff --git a/clang/lib/CodeGen/CGCleanup.cpp b/clang/lib/CodeGen/CGCleanup.cpp index e6f8e6873004f29d716caea0e82fb902be0f8117..469e0363b744acf63943ecead6f79173e8f0ae5e 100644 --- a/clang/lib/CodeGen/CGCleanup.cpp +++ b/clang/lib/CodeGen/CGCleanup.cpp @@ -634,12 +634,19 @@ static void destroyOptimisticNormalEntry(CodeGenFunction &CGF, /// Pops a cleanup block. If the block includes a normal cleanup, the /// current insertion point is threaded through the cleanup, as are /// any branch fixups on the cleanup. -void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) { +void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough, + bool ForDeactivation) { assert(!EHStack.empty() && "cleanup stack is empty!"); assert(isa(*EHStack.begin()) && "top not a cleanup!"); EHCleanupScope &Scope = cast(*EHStack.begin()); assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups()); + // If we are deactivating a normal cleanup, we need to pretend that the + // fallthrough is unreachable. We restore this IP before returning. + CGBuilderTy::InsertPoint NormalDeactivateOrigIP; + if (ForDeactivation && (Scope.isNormalCleanup() || !getLangOpts().EHAsynch)) { + NormalDeactivateOrigIP = Builder.saveAndClearIP(); + } // Remember activation information. bool IsActive = Scope.isActive(); Address NormalActiveFlag = @@ -667,7 +674,8 @@ void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) { // - whether there's a fallthrough llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock(); - bool HasFallthrough = (FallthroughSource != nullptr && IsActive); + bool HasFallthrough = + FallthroughSource != nullptr && (IsActive || HasExistingBranches); // Branch-through fall-throughs leave the insertion point set to the // end of the last cleanup, which points to the current scope. The @@ -692,7 +700,11 @@ void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) { // If we have a prebranched fallthrough into an inactive normal // cleanup, rewrite it so that it leads to the appropriate place. - if (Scope.isNormalCleanup() && HasPrebranchedFallthrough && !IsActive) { + if (Scope.isNormalCleanup() && HasPrebranchedFallthrough && + !RequiresNormalCleanup) { + // FIXME: Come up with a program which would need forwarding prebranched + // fallthrough and add tests. Otherwise delete this and assert against it. + assert(!IsActive); llvm::BasicBlock *prebranchDest; // If the prebranch is semantically branching through the next @@ -724,6 +736,8 @@ void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) { EHStack.popCleanup(); // safe because there are no fixups assert(EHStack.getNumBranchFixups() == 0 || EHStack.hasNormalCleanups()); + if (NormalDeactivateOrigIP.isSet()) + Builder.restoreIP(NormalDeactivateOrigIP); return; } @@ -760,11 +774,19 @@ void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) { if (!RequiresNormalCleanup) { // Mark CPP scope end for passed-by-value Arg temp // per Windows ABI which is "normally" Cleanup in callee - if (IsEHa && getInvokeDest() && Builder.GetInsertBlock()) { - if (Personality.isMSVCXXPersonality()) + if (IsEHa && getInvokeDest()) { + // If we are deactivating a normal cleanup then we don't have a + // fallthrough. Restore original IP to emit CPP scope ends in the correct + // block. + if (NormalDeactivateOrigIP.isSet()) + Builder.restoreIP(NormalDeactivateOrigIP); + if (Personality.isMSVCXXPersonality() && Builder.GetInsertBlock()) EmitSehCppScopeEnd(); + if (NormalDeactivateOrigIP.isSet()) + NormalDeactivateOrigIP = Builder.saveAndClearIP(); } destroyOptimisticNormalEntry(*this, Scope); + Scope.MarkEmitted(); EHStack.popCleanup(); } else { // If we have a fallthrough and no other need for the cleanup, @@ -781,6 +803,7 @@ void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) { } destroyOptimisticNormalEntry(*this, Scope); + Scope.MarkEmitted(); EHStack.popCleanup(); EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag); @@ -916,6 +939,7 @@ void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) { } // IV. Pop the cleanup and emit it. + Scope.MarkEmitted(); EHStack.popCleanup(); assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups); @@ -984,6 +1008,8 @@ void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) { } } + if (NormalDeactivateOrigIP.isSet()) + Builder.restoreIP(NormalDeactivateOrigIP); assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0); // Emit the EH cleanup if required. @@ -1143,25 +1169,6 @@ void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) { Builder.ClearInsertionPoint(); } -static bool IsUsedAsNormalCleanup(EHScopeStack &EHStack, - EHScopeStack::stable_iterator C) { - // If we needed a normal block for any reason, that counts. - if (cast(*EHStack.find(C)).getNormalBlock()) - return true; - - // Check whether any enclosed cleanups were needed. - for (EHScopeStack::stable_iterator - I = EHStack.getInnermostNormalCleanup(); - I != C; ) { - assert(C.strictlyEncloses(I)); - EHCleanupScope &S = cast(*EHStack.find(I)); - if (S.getNormalBlock()) return true; - I = S.getEnclosingNormalCleanup(); - } - - return false; -} - static bool IsUsedAsEHCleanup(EHScopeStack &EHStack, EHScopeStack::stable_iterator cleanup) { // If we needed an EH block for any reason, that counts. @@ -1210,8 +1217,7 @@ static void SetupCleanupBlockActivation(CodeGenFunction &CGF, // Calculate whether the cleanup was used: // - as a normal cleanup - if (Scope.isNormalCleanup() && - (isActivatedInConditional || IsUsedAsNormalCleanup(CGF.EHStack, C))) { + if (Scope.isNormalCleanup()) { Scope.setTestFlagInNormalCleanup(); needFlag = true; } @@ -1224,13 +1230,16 @@ static void SetupCleanupBlockActivation(CodeGenFunction &CGF, } // If it hasn't yet been used as either, we're done. - if (!needFlag) return; + if (!needFlag) + return; Address var = Scope.getActiveFlag(); if (!var.isValid()) { + CodeGenFunction::AllocaTrackerRAII AllocaTracker(CGF); var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), CharUnits::One(), "cleanup.isactive"); Scope.setActiveFlag(var); + Scope.AddAuxAllocas(AllocaTracker.Take()); assert(dominatingIP && "no existing variable and no dominating IP!"); @@ -1273,17 +1282,8 @@ void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C, // to the current RunCleanupsScope. if (C == EHStack.stable_begin() && CurrentCleanupScopeDepth.strictlyEncloses(C)) { - // Per comment below, checking EHAsynch is not really necessary - // it's there to assure zero-impact w/o EHAsynch option - if (!Scope.isNormalCleanup() && getLangOpts().EHAsynch) { - PopCleanupBlock(); - } else { - // If it's a normal cleanup, we need to pretend that the - // fallthrough is unreachable. - CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP(); - PopCleanupBlock(); - Builder.restoreIP(SavedIP); - } + PopCleanupBlock(/*FallthroughIsBranchThrough=*/false, + /*ForDeactivation=*/true); return; } diff --git a/clang/lib/CodeGen/CGCleanup.h b/clang/lib/CodeGen/CGCleanup.h index 03e4a29d7b3dbfa5b3953725e9fc1fe0fe55bb44..c73c97146abc4d4d5ec4adba51bf0a02106d7d89 100644 --- a/clang/lib/CodeGen/CGCleanup.h +++ b/clang/lib/CodeGen/CGCleanup.h @@ -16,8 +16,11 @@ #include "EHScopeStack.h" #include "Address.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" +#include "llvm/IR/Instruction.h" namespace llvm { class BasicBlock; @@ -266,6 +269,51 @@ class alignas(8) EHCleanupScope : public EHScope { }; mutable struct ExtInfo *ExtInfo; + /// Erases auxillary allocas and their usages for an unused cleanup. + /// Cleanups should mark these allocas as 'used' if the cleanup is + /// emitted, otherwise these instructions would be erased. + struct AuxillaryAllocas { + SmallVector AuxAllocas; + bool used = false; + + // Records a potentially unused instruction to be erased later. + void Add(llvm::AllocaInst *Alloca) { AuxAllocas.push_back(Alloca); } + + // Mark all recorded instructions as used. These will not be erased later. + void MarkUsed() { + used = true; + AuxAllocas.clear(); + } + + ~AuxillaryAllocas() { + if (used) + return; + llvm::SetVector Uses; + for (auto *Inst : llvm::reverse(AuxAllocas)) + CollectUses(Inst, Uses); + // Delete uses in the reverse order of insertion. + for (auto *I : llvm::reverse(Uses)) + I->eraseFromParent(); + } + + private: + void CollectUses(llvm::Instruction *I, + llvm::SetVector &Uses) { + if (!I || !Uses.insert(I)) + return; + for (auto *User : I->users()) + CollectUses(cast(User), Uses); + } + }; + mutable struct AuxillaryAllocas *AuxAllocas; + + AuxillaryAllocas &getAuxillaryAllocas() { + if (!AuxAllocas) { + AuxAllocas = new struct AuxillaryAllocas(); + } + return *AuxAllocas; + } + /// The number of fixups required by enclosing scopes (not including /// this one). If this is the top cleanup scope, all the fixups /// from this index onwards belong to this scope. @@ -298,7 +346,7 @@ public: EHScopeStack::stable_iterator enclosingEH) : EHScope(EHScope::Cleanup, enclosingEH), EnclosingNormal(enclosingNormal), NormalBlock(nullptr), - ActiveFlag(Address::invalid()), ExtInfo(nullptr), + ActiveFlag(Address::invalid()), ExtInfo(nullptr), AuxAllocas(nullptr), FixupDepth(fixupDepth) { CleanupBits.IsNormalCleanup = isNormal; CleanupBits.IsEHCleanup = isEH; @@ -312,8 +360,15 @@ public: } void Destroy() { + if (AuxAllocas) + delete AuxAllocas; delete ExtInfo; } + void AddAuxAllocas(llvm::SmallVector Allocas) { + for (auto *Alloca : Allocas) + getAuxillaryAllocas().Add(Alloca); + } + void MarkEmitted() { getAuxillaryAllocas().MarkUsed(); } // Objects of EHCleanupScope are not destructed. Use Destroy(). ~EHCleanupScope() = delete; diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp b/clang/lib/CodeGen/CGDebugInfo.cpp index 787db350487417c0013c42e0f4625968a677105b..fac278f0e20a438102c913384af3e48185e11c96 100644 --- a/clang/lib/CodeGen/CGDebugInfo.cpp +++ b/clang/lib/CodeGen/CGDebugInfo.cpp @@ -1373,6 +1373,8 @@ llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty, SourceLocation Loc = AliasDecl->getLocation(); if (CGM.getCodeGenOpts().DebugTemplateAlias && + // FIXME: This is a workaround for the issue + // https://github.com/llvm/llvm-project/issues/89774 // The TemplateSpecializationType doesn't contain any instantiation // information; dependent template arguments can't be resolved. For now, // fall back to DW_TAG_typedefs for template aliases that are diff --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp index ce6d6d8956076e4966eb0fd6719e1ab4f9a00af3..9cc67cdbe424b4022dc59c6cbad188744daef92a 100644 --- a/clang/lib/CodeGen/CGDecl.cpp +++ b/clang/lib/CodeGen/CGDecl.cpp @@ -19,6 +19,7 @@ #include "CodeGenFunction.h" #include "CodeGenModule.h" #include "ConstantEmitter.h" +#include "EHScopeStack.h" #include "PatternInit.h" #include "TargetInfo.h" #include "clang/AST/ASTContext.h" @@ -35,6 +36,7 @@ #include "llvm/Analysis/ValueTracking.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/GlobalVariable.h" +#include "llvm/IR/Instructions.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/Type.h" #include @@ -2201,6 +2203,27 @@ void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr, destroyer, useEHCleanupForArray); } +// Pushes a destroy and defers its deactivation until its +// CleanupDeactivationScope is exited. +void CodeGenFunction::pushDestroyAndDeferDeactivation( + QualType::DestructionKind dtorKind, Address addr, QualType type) { + assert(dtorKind && "cannot push destructor for trivial type"); + + CleanupKind cleanupKind = getCleanupKind(dtorKind); + pushDestroyAndDeferDeactivation( + cleanupKind, addr, type, getDestroyer(dtorKind), cleanupKind & EHCleanup); +} + +void CodeGenFunction::pushDestroyAndDeferDeactivation( + CleanupKind cleanupKind, Address addr, QualType type, Destroyer *destroyer, + bool useEHCleanupForArray) { + llvm::Instruction *DominatingIP = + Builder.CreateFlagLoad(llvm::Constant::getNullValue(Int8PtrTy)); + pushDestroy(cleanupKind, addr, type, destroyer, useEHCleanupForArray); + DeferredDeactivationCleanupStack.push_back( + {EHStack.stable_begin(), DominatingIP}); +} + void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) { EHStack.pushCleanup(Kind, SPMem); } @@ -2217,39 +2240,48 @@ void CodeGenFunction::pushLifetimeExtendedDestroy(CleanupKind cleanupKind, // If we're not in a conditional branch, we don't need to bother generating a // conditional cleanup. if (!isInConditionalBranch()) { - // Push an EH-only cleanup for the object now. // FIXME: When popping normal cleanups, we need to keep this EH cleanup // around in case a temporary's destructor throws an exception. - if (cleanupKind & EHCleanup) - EHStack.pushCleanup( - static_cast(cleanupKind & ~NormalCleanup), addr, type, - destroyer, useEHCleanupForArray); + // Add the cleanup to the EHStack. After the full-expr, this would be + // deactivated before being popped from the stack. + pushDestroyAndDeferDeactivation(cleanupKind, addr, type, destroyer, + useEHCleanupForArray); + + // Since this is lifetime-extended, push it once again to the EHStack after + // the full expression. return pushCleanupAfterFullExprWithActiveFlag( - cleanupKind, Address::invalid(), addr, type, destroyer, useEHCleanupForArray); + cleanupKind, Address::invalid(), addr, type, destroyer, + useEHCleanupForArray); } // Otherwise, we should only destroy the object if it's been initialized. - // Re-use the active flag and saved address across both the EH and end of - // scope cleanups. - using SavedType = typename DominatingValue
::saved_type; using ConditionalCleanupType = EHScopeStack::ConditionalCleanup; - - Address ActiveFlag = createCleanupActiveFlag(); - SavedType SavedAddr = saveValueInCond(addr); - - if (cleanupKind & EHCleanup) { - EHStack.pushCleanup( - static_cast(cleanupKind & ~NormalCleanup), SavedAddr, type, - destroyer, useEHCleanupForArray); - initFullExprCleanupWithFlag(ActiveFlag); - } - + DominatingValue
::saved_type SavedAddr = saveValueInCond(addr); + + // Remember to emit cleanup if we branch-out before end of full-expression + // (eg: through stmt-expr or coro suspensions). + AllocaTrackerRAII DeactivationAllocas(*this); + Address ActiveFlagForDeactivation = createCleanupActiveFlag(); + + pushCleanupAndDeferDeactivation( + cleanupKind, SavedAddr, type, destroyer, useEHCleanupForArray); + initFullExprCleanupWithFlag(ActiveFlagForDeactivation); + EHCleanupScope &cleanup = cast(*EHStack.begin()); + // Erase the active flag if the cleanup was not emitted. + cleanup.AddAuxAllocas(std::move(DeactivationAllocas).Take()); + + // Since this is lifetime-extended, push it once again to the EHStack after + // the full expression. + // The previous active flag would always be 'false' due to forced deferred + // deactivation. Use a separate flag for lifetime-extension to correctly + // remember if this branch was taken and the object was initialized. + Address ActiveFlagForLifetimeExt = createCleanupActiveFlag(); pushCleanupAfterFullExprWithActiveFlag( - cleanupKind, ActiveFlag, SavedAddr, type, destroyer, + cleanupKind, ActiveFlagForLifetimeExt, SavedAddr, type, destroyer, useEHCleanupForArray); } @@ -2442,9 +2474,9 @@ namespace { }; } // end anonymous namespace -/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy -/// already-constructed elements of the given array. The cleanup -/// may be popped with DeactivateCleanupBlock or PopCleanupBlock. +/// pushIrregularPartialArrayCleanup - Push a NormalAndEHCleanup to +/// destroy already-constructed elements of the given array. The cleanup may be +/// popped with DeactivateCleanupBlock or PopCleanupBlock. /// /// \param elementType - the immediate element type of the array; /// possibly still an array type @@ -2453,10 +2485,9 @@ void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, QualType elementType, CharUnits elementAlign, Destroyer *destroyer) { - pushFullExprCleanup(EHCleanup, - arrayBegin, arrayEndPointer, - elementType, elementAlign, - destroyer); + pushFullExprCleanup( + NormalAndEHCleanup, arrayBegin, arrayEndPointer, elementType, + elementAlign, destroyer); } /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp index c94322f51e46cfa71e9310bfd69aac7ed2b25a68..d96c7bb1e56822f108ad5a17839f48253d7bfb51 100644 --- a/clang/lib/CodeGen/CGExpr.cpp +++ b/clang/lib/CodeGen/CGExpr.cpp @@ -115,10 +115,16 @@ RawAddress CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align, llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, const Twine &Name, llvm::Value *ArraySize) { + llvm::AllocaInst *Alloca; if (ArraySize) - return Builder.CreateAlloca(Ty, ArraySize, Name); - return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(), - ArraySize, Name, AllocaInsertPt); + Alloca = Builder.CreateAlloca(Ty, ArraySize, Name); + else + Alloca = new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(), + ArraySize, Name, AllocaInsertPt); + if (Allocas) { + Allocas->Add(Alloca); + } + return Alloca; } /// CreateDefaultAlignTempAlloca - This creates an alloca with the diff --git a/clang/lib/CodeGen/CGExprAgg.cpp b/clang/lib/CodeGen/CGExprAgg.cpp index 355fec42be4489389fa71aa73b948afbf9701069..44d476976a55bf4392ca733dae2e88e0f1e2909c 100644 --- a/clang/lib/CodeGen/CGExprAgg.cpp +++ b/clang/lib/CodeGen/CGExprAgg.cpp @@ -15,6 +15,7 @@ #include "CodeGenFunction.h" #include "CodeGenModule.h" #include "ConstantEmitter.h" +#include "EHScopeStack.h" #include "TargetInfo.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Attr.h" @@ -24,6 +25,7 @@ #include "llvm/IR/Constants.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalVariable.h" +#include "llvm/IR/Instruction.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Intrinsics.h" using namespace clang; @@ -558,24 +560,27 @@ void AggExprEmitter::EmitArrayInit(Address DestPtr, llvm::ArrayType *AType, // For that, we'll need an EH cleanup. QualType::DestructionKind dtorKind = elementType.isDestructedType(); Address endOfInit = Address::invalid(); - EHScopeStack::stable_iterator cleanup; - llvm::Instruction *cleanupDominator = nullptr; - if (CGF.needsEHCleanup(dtorKind)) { + CodeGenFunction::CleanupDeactivationScope deactivation(CGF); + + if (dtorKind) { + CodeGenFunction::AllocaTrackerRAII allocaTracker(CGF); // In principle we could tell the cleanup where we are more // directly, but the control flow can get so varied here that it // would actually be quite complex. Therefore we go through an // alloca. + llvm::Instruction *dominatingIP = + Builder.CreateFlagLoad(llvm::ConstantInt::getNullValue(CGF.Int8PtrTy)); endOfInit = CGF.CreateTempAlloca(begin->getType(), CGF.getPointerAlign(), "arrayinit.endOfInit"); - cleanupDominator = Builder.CreateStore(begin, endOfInit); + Builder.CreateStore(begin, endOfInit); CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType, elementAlign, CGF.getDestroyer(dtorKind)); - cleanup = CGF.EHStack.stable_begin(); + cast(*CGF.EHStack.find(CGF.EHStack.stable_begin())) + .AddAuxAllocas(allocaTracker.Take()); - // Otherwise, remember that we didn't need a cleanup. - } else { - dtorKind = QualType::DK_none; + CGF.DeferredDeactivationCleanupStack.push_back( + {CGF.EHStack.stable_begin(), dominatingIP}); } llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1); @@ -671,9 +676,6 @@ void AggExprEmitter::EmitArrayInit(Address DestPtr, llvm::ArrayType *AType, CGF.EmitBlock(endBB); } - - // Leave the partial-array cleanup if we entered one. - if (dtorKind) CGF.DeactivateCleanupBlock(cleanup, cleanupDominator); } //===----------------------------------------------------------------------===// @@ -1374,9 +1376,8 @@ AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) { LValue SlotLV = CGF.MakeAddrLValue(Slot.getAddress(), E->getType()); // We'll need to enter cleanup scopes in case any of the element - // initializers throws an exception. - SmallVector Cleanups; - llvm::Instruction *CleanupDominator = nullptr; + // initializers throws an exception or contains branch out of the expressions. + CodeGenFunction::CleanupDeactivationScope scope(CGF); CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin(); for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(), @@ -1395,28 +1396,12 @@ AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) { if (QualType::DestructionKind DtorKind = CurField->getType().isDestructedType()) { assert(LV.isSimple()); - if (CGF.needsEHCleanup(DtorKind)) { - if (!CleanupDominator) - CleanupDominator = CGF.Builder.CreateAlignedLoad( - CGF.Int8Ty, - llvm::Constant::getNullValue(CGF.Int8PtrTy), - CharUnits::One()); // placeholder - - CGF.pushDestroy(EHCleanup, LV.getAddress(CGF), CurField->getType(), - CGF.getDestroyer(DtorKind), false); - Cleanups.push_back(CGF.EHStack.stable_begin()); - } + if (DtorKind) + CGF.pushDestroyAndDeferDeactivation( + NormalAndEHCleanup, LV.getAddress(CGF), CurField->getType(), + CGF.getDestroyer(DtorKind), false); } } - - // Deactivate all the partial cleanups in reverse order, which - // generally means popping them. - for (unsigned i = Cleanups.size(); i != 0; --i) - CGF.DeactivateCleanupBlock(Cleanups[i-1], CleanupDominator); - - // Destroy the placeholder if we made one. - if (CleanupDominator) - CleanupDominator->eraseFromParent(); } void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) { @@ -1705,14 +1690,7 @@ void AggExprEmitter::VisitCXXParenListOrInitListExpr( // We'll need to enter cleanup scopes in case any of the element // initializers throws an exception. SmallVector cleanups; - llvm::Instruction *cleanupDominator = nullptr; - auto addCleanup = [&](const EHScopeStack::stable_iterator &cleanup) { - cleanups.push_back(cleanup); - if (!cleanupDominator) // create placeholder once needed - cleanupDominator = CGF.Builder.CreateAlignedLoad( - CGF.Int8Ty, llvm::Constant::getNullValue(CGF.Int8PtrTy), - CharUnits::One()); - }; + CodeGenFunction::CleanupDeactivationScope DeactivateCleanups(CGF); unsigned curInitIndex = 0; @@ -1735,10 +1713,8 @@ void AggExprEmitter::VisitCXXParenListOrInitListExpr( CGF.EmitAggExpr(InitExprs[curInitIndex++], AggSlot); if (QualType::DestructionKind dtorKind = - Base.getType().isDestructedType()) { - CGF.pushDestroy(dtorKind, V, Base.getType()); - addCleanup(CGF.EHStack.stable_begin()); - } + Base.getType().isDestructedType()) + CGF.pushDestroyAndDeferDeactivation(dtorKind, V, Base.getType()); } } @@ -1815,10 +1791,10 @@ void AggExprEmitter::VisitCXXParenListOrInitListExpr( if (QualType::DestructionKind dtorKind = field->getType().isDestructedType()) { assert(LV.isSimple()); - if (CGF.needsEHCleanup(dtorKind)) { - CGF.pushDestroy(EHCleanup, LV.getAddress(CGF), field->getType(), - CGF.getDestroyer(dtorKind), false); - addCleanup(CGF.EHStack.stable_begin()); + if (dtorKind) { + CGF.pushDestroyAndDeferDeactivation( + NormalAndEHCleanup, LV.getAddress(CGF), field->getType(), + CGF.getDestroyer(dtorKind), false); pushedCleanup = true; } } @@ -1831,17 +1807,6 @@ void AggExprEmitter::VisitCXXParenListOrInitListExpr( if (GEP->use_empty()) GEP->eraseFromParent(); } - - // Deactivate all the partial cleanups in reverse order, which - // generally means popping them. - assert((cleanupDominator || cleanups.empty()) && - "Missing cleanupDominator before deactivating cleanup blocks"); - for (unsigned i = cleanups.size(); i != 0; --i) - CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator); - - // Destroy the placeholder if we made one. - if (cleanupDominator) - cleanupDominator->eraseFromParent(); } void AggExprEmitter::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E, diff --git a/clang/lib/CodeGen/CGExprCXX.cpp b/clang/lib/CodeGen/CGExprCXX.cpp index 673ccef84d67814dd27bdd54bcc168f28540ae92..c18c36d3f3f3267fba9906f2c81092b8bfe3ff94 100644 --- a/clang/lib/CodeGen/CGExprCXX.cpp +++ b/clang/lib/CodeGen/CGExprCXX.cpp @@ -1008,8 +1008,8 @@ void CodeGenFunction::EmitNewArrayInitializer( const Expr *Init = E->getInitializer(); Address EndOfInit = Address::invalid(); QualType::DestructionKind DtorKind = ElementType.isDestructedType(); - EHScopeStack::stable_iterator Cleanup; - llvm::Instruction *CleanupDominator = nullptr; + CleanupDeactivationScope deactivation(*this); + bool pushedCleanup = false; CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType); CharUnits ElementAlign = @@ -1105,19 +1105,24 @@ void CodeGenFunction::EmitNewArrayInitializer( } // Enter a partial-destruction Cleanup if necessary. - if (needsEHCleanup(DtorKind)) { + if (DtorKind) { + AllocaTrackerRAII AllocaTracker(*this); // In principle we could tell the Cleanup where we are more // directly, but the control flow can get so varied here that it // would actually be quite complex. Therefore we go through an // alloca. + llvm::Instruction *DominatingIP = + Builder.CreateFlagLoad(llvm::ConstantInt::getNullValue(Int8PtrTy)); EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(), "array.init.end"); - CleanupDominator = - Builder.CreateStore(BeginPtr.emitRawPointer(*this), EndOfInit); pushIrregularPartialArrayCleanup(BeginPtr.emitRawPointer(*this), EndOfInit, ElementType, ElementAlign, getDestroyer(DtorKind)); - Cleanup = EHStack.stable_begin(); + cast(*EHStack.find(EHStack.stable_begin())) + .AddAuxAllocas(AllocaTracker.Take()); + DeferredDeactivationCleanupStack.push_back( + {EHStack.stable_begin(), DominatingIP}); + pushedCleanup = true; } CharUnits StartAlign = CurPtr.getAlignment(); @@ -1164,9 +1169,6 @@ void CodeGenFunction::EmitNewArrayInitializer( // initialization. llvm::ConstantInt *ConstNum = dyn_cast(NumElements); if (ConstNum && ConstNum->getZExtValue() <= InitListElements) { - // If there was a Cleanup, deactivate it. - if (CleanupDominator) - DeactivateCleanupBlock(Cleanup, CleanupDominator); return; } @@ -1281,13 +1283,14 @@ void CodeGenFunction::EmitNewArrayInitializer( Builder.CreateStore(CurPtr.emitRawPointer(*this), EndOfInit); // Enter a partial-destruction Cleanup if necessary. - if (!CleanupDominator && needsEHCleanup(DtorKind)) { - llvm::Value *BeginPtrRaw = BeginPtr.emitRawPointer(*this); - llvm::Value *CurPtrRaw = CurPtr.emitRawPointer(*this); - pushRegularPartialArrayCleanup(BeginPtrRaw, CurPtrRaw, ElementType, + if (!pushedCleanup && needsEHCleanup(DtorKind)) { + llvm::Instruction *DominatingIP = + Builder.CreateFlagLoad(llvm::ConstantInt::getNullValue(Int8PtrTy)); + pushRegularPartialArrayCleanup(BeginPtr.emitRawPointer(*this), + CurPtr.emitRawPointer(*this), ElementType, ElementAlign, getDestroyer(DtorKind)); - Cleanup = EHStack.stable_begin(); - CleanupDominator = Builder.CreateUnreachable(); + DeferredDeactivationCleanupStack.push_back( + {EHStack.stable_begin(), DominatingIP}); } // Emit the initializer into this element. @@ -1295,10 +1298,7 @@ void CodeGenFunction::EmitNewArrayInitializer( AggValueSlot::DoesNotOverlap); // Leave the Cleanup if we entered one. - if (CleanupDominator) { - DeactivateCleanupBlock(Cleanup, CleanupDominator); - CleanupDominator->eraseFromParent(); - } + deactivation.ForceDeactivate(); // Advance to the next element by adjusting the pointer type as necessary. llvm::Value *NextPtr = Builder.CreateConstInBoundsGEP1_32( diff --git a/clang/lib/CodeGen/CGExprScalar.cpp b/clang/lib/CodeGen/CGExprScalar.cpp index 40a5cd20c3d715a343f1e44866000641be07d5c4..af48e8d2b839e0c023e54ee2e0151d4b45b3e3f0 100644 --- a/clang/lib/CodeGen/CGExprScalar.cpp +++ b/clang/lib/CodeGen/CGExprScalar.cpp @@ -2330,7 +2330,7 @@ Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) { } // Perform VLAT <-> VLST bitcast through memory. - // TODO: since the llvm.experimental.vector.{insert,extract} intrinsics + // TODO: since the llvm.vector.{insert,extract} intrinsics // require the element types of the vectors to be the same, we // need to keep this around for bitcasts between VLAT <-> VLST where // the element types of the vectors are not the same, until we figure diff --git a/clang/lib/CodeGen/CGLoopInfo.cpp b/clang/lib/CodeGen/CGLoopInfo.cpp index 72d1471021ac02971f8d4da33e0ef149df12a501..0d4800b90a2f26c67ba51fff219673fb5290a8e4 100644 --- a/clang/lib/CodeGen/CGLoopInfo.cpp +++ b/clang/lib/CodeGen/CGLoopInfo.cpp @@ -673,8 +673,6 @@ void LoopInfoStack::push(BasicBlock *Header, clang::ASTContext &Ctx, setPipelineDisabled(true); break; case LoopHintAttr::UnrollCount: - setUnrollState(LoopAttributes::Disable); - break; case LoopHintAttr::UnrollAndJamCount: case LoopHintAttr::VectorizeWidth: case LoopHintAttr::InterleaveCount: diff --git a/clang/lib/CodeGen/CMakeLists.txt b/clang/lib/CodeGen/CMakeLists.txt index 52216d93a302bbb18715ec1af9de4c5aa9b78e6b..7a933d0ed0d0d7d84a813be8b6033b85798ae420 100644 --- a/clang/lib/CodeGen/CMakeLists.txt +++ b/clang/lib/CodeGen/CMakeLists.txt @@ -143,6 +143,9 @@ add_clang_library(clangCodeGen DEPENDS intrinsics_gen ClangDriverOptions + # These generated headers are included transitively. + ARMTargetParserTableGen + AArch64TargetParserTableGen LINK_LIBS clangAST diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp b/clang/lib/CodeGen/CodeGenFunction.cpp index 86a6ddd80cc11464aa65b310fe050f44dbe12217..87766a758311d5f0e2b50e5a8dc8b58535735a30 100644 --- a/clang/lib/CodeGen/CodeGenFunction.cpp +++ b/clang/lib/CodeGen/CodeGenFunction.cpp @@ -91,6 +91,8 @@ CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext) CodeGenFunction::~CodeGenFunction() { assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup"); + assert(DeferredDeactivationCleanupStack.empty() && + "missed to deactivate a cleanup"); if (getLangOpts().OpenMP && CurFn) CGM.getOpenMPRuntime().functionFinished(*this); @@ -346,6 +348,10 @@ static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) { void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { assert(BreakContinueStack.empty() && "mismatched push/pop in break/continue stack!"); + assert(LifetimeExtendedCleanupStack.empty() && + "mismatched push/pop of cleanups in EHStack!"); + assert(DeferredDeactivationCleanupStack.empty() && + "mismatched activate/deactivate of cleanups!"); bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0 && NumSimpleReturnExprs == NumReturnExprs diff --git a/clang/lib/CodeGen/CodeGenFunction.h b/clang/lib/CodeGen/CodeGenFunction.h index 33fb7a41912b520bf29b33b0cfed754e14aaf727..6e7417fc7f52b679c26bcf7fd0aa5d0a3f8c60a7 100644 --- a/clang/lib/CodeGen/CodeGenFunction.h +++ b/clang/lib/CodeGen/CodeGenFunction.h @@ -39,6 +39,7 @@ #include "llvm/ADT/MapVector.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" +#include "llvm/IR/Instructions.h" #include "llvm/IR/ValueHandle.h" #include "llvm/Support/Debug.h" #include "llvm/Transforms/Utils/SanitizerStats.h" @@ -670,6 +671,51 @@ public: EHScopeStack EHStack; llvm::SmallVector LifetimeExtendedCleanupStack; + + // A stack of cleanups which were added to EHStack but have to be deactivated + // later before being popped or emitted. These are usually deactivated on + // exiting a `CleanupDeactivationScope` scope. For instance, after a + // full-expr. + // + // These are specially useful for correctly emitting cleanups while + // encountering branches out of expression (through stmt-expr or coroutine + // suspensions). + struct DeferredDeactivateCleanup { + EHScopeStack::stable_iterator Cleanup; + llvm::Instruction *DominatingIP; + }; + llvm::SmallVector DeferredDeactivationCleanupStack; + + // Enters a new scope for capturing cleanups which are deferred to be + // deactivated, all of which will be deactivated once the scope is exited. + struct CleanupDeactivationScope { + CodeGenFunction &CGF; + size_t OldDeactivateCleanupStackSize; + bool Deactivated; + CleanupDeactivationScope(CodeGenFunction &CGF) + : CGF(CGF), OldDeactivateCleanupStackSize( + CGF.DeferredDeactivationCleanupStack.size()), + Deactivated(false) {} + + void ForceDeactivate() { + assert(!Deactivated && "Deactivating already deactivated scope"); + auto &Stack = CGF.DeferredDeactivationCleanupStack; + for (size_t I = Stack.size(); I > OldDeactivateCleanupStackSize; I--) { + CGF.DeactivateCleanupBlock(Stack[I - 1].Cleanup, + Stack[I - 1].DominatingIP); + Stack[I - 1].DominatingIP->eraseFromParent(); + } + Stack.resize(OldDeactivateCleanupStackSize); + Deactivated = true; + } + + ~CleanupDeactivationScope() { + if (Deactivated) + return; + ForceDeactivate(); + } + }; + llvm::SmallVector SEHTryEpilogueStack; llvm::Instruction *CurrentFuncletPad = nullptr; @@ -875,6 +921,19 @@ public: new (Buffer + sizeof(Header) + sizeof(T)) RawAddress(ActiveFlag); } + // Push a cleanup onto EHStack and deactivate it later. It is usually + // deactivated when exiting a `CleanupDeactivationScope` (for example: after a + // full expression). + template + void pushCleanupAndDeferDeactivation(CleanupKind Kind, As... A) { + // Placeholder dominating IP for this cleanup. + llvm::Instruction *DominatingIP = + Builder.CreateFlagLoad(llvm::Constant::getNullValue(Int8PtrTy)); + EHStack.pushCleanup(Kind, A...); + DeferredDeactivationCleanupStack.push_back( + {EHStack.stable_begin(), DominatingIP}); + } + /// Set up the last cleanup that was pushed as a conditional /// full-expression cleanup. void initFullExprCleanup() { @@ -898,7 +957,8 @@ public: /// PopCleanupBlock - Will pop the cleanup entry on the stack and /// process all branch fixups. - void PopCleanupBlock(bool FallThroughIsBranchThrough = false); + void PopCleanupBlock(bool FallThroughIsBranchThrough = false, + bool ForDeactivation = false); /// DeactivateCleanupBlock - Deactivates the given cleanup block. /// The block cannot be reactivated. Pops it if it's the top of the @@ -926,6 +986,7 @@ public: class RunCleanupsScope { EHScopeStack::stable_iterator CleanupStackDepth, OldCleanupScopeDepth; size_t LifetimeExtendedCleanupStackSize; + CleanupDeactivationScope DeactivateCleanups; bool OldDidCallStackSave; protected: bool PerformCleanup; @@ -940,8 +1001,7 @@ public: public: /// Enter a new cleanup scope. explicit RunCleanupsScope(CodeGenFunction &CGF) - : PerformCleanup(true), CGF(CGF) - { + : DeactivateCleanups(CGF), PerformCleanup(true), CGF(CGF) { CleanupStackDepth = CGF.EHStack.stable_begin(); LifetimeExtendedCleanupStackSize = CGF.LifetimeExtendedCleanupStack.size(); @@ -971,6 +1031,7 @@ public: void ForceCleanup(std::initializer_list ValuesToReload = {}) { assert(PerformCleanup && "Already forced cleanup"); CGF.DidCallStackSave = OldDidCallStackSave; + DeactivateCleanups.ForceDeactivate(); CGF.PopCleanupBlocks(CleanupStackDepth, LifetimeExtendedCleanupStackSize, ValuesToReload); PerformCleanup = false; @@ -2160,6 +2221,11 @@ public: Address addr, QualType type); void pushDestroy(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray); + void pushDestroyAndDeferDeactivation(QualType::DestructionKind dtorKind, + Address addr, QualType type); + void pushDestroyAndDeferDeactivation(CleanupKind cleanupKind, Address addr, + QualType type, Destroyer *destroyer, + bool useEHCleanupForArray); void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray); @@ -2698,6 +2764,33 @@ public: TBAAAccessInfo *TBAAInfo = nullptr); LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy); +private: + struct AllocaTracker { + void Add(llvm::AllocaInst *I) { Allocas.push_back(I); } + llvm::SmallVector Take() { return std::move(Allocas); } + + private: + llvm::SmallVector Allocas; + }; + AllocaTracker *Allocas = nullptr; + +public: + // Captures all the allocas created during the scope of its RAII object. + struct AllocaTrackerRAII { + AllocaTrackerRAII(CodeGenFunction &CGF) + : CGF(CGF), OldTracker(CGF.Allocas) { + CGF.Allocas = &Tracker; + } + ~AllocaTrackerRAII() { CGF.Allocas = OldTracker; } + + llvm::SmallVector Take() { return Tracker.Take(); } + + private: + CodeGenFunction &CGF; + AllocaTracker *OldTracker; + AllocaTracker Tracker; + }; + /// CreateTempAlloca - This creates an alloca and inserts it into the entry /// block if \p ArraySize is nullptr, otherwise inserts it at the current /// insertion point of the builder. The caller is responsible for setting an diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp index d085e735ecb443a1bc59f9dea2ba4ae319ac56ae..c8898ce196c1edb0010ba49c3c699b663d0f9845 100644 --- a/clang/lib/CodeGen/CodeGenModule.cpp +++ b/clang/lib/CodeGen/CodeGenModule.cpp @@ -73,6 +73,7 @@ #include "llvm/TargetParser/RISCVISAInfo.h" #include "llvm/TargetParser/Triple.h" #include "llvm/TargetParser/X86TargetParser.h" +#include "llvm/Transforms/Utils/BuildLibCalls.h" #include using namespace clang; @@ -442,6 +443,11 @@ CodeGenModule::CodeGenModule(ASTContext &C, } ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path); } + + // Record mregparm value now so it is visible through all of codegen. + if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) + getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters", + CodeGenOpts.NumRegisterParameters); } CodeGenModule::~CodeGenModule() {} @@ -980,11 +986,6 @@ void CodeGenModule::Release() { NMD->addOperand(MD); } - // Record mregparm value now so it is visible through rest of codegen. - if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) - getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters", - CodeGenOpts.NumRegisterParameters); - if (CodeGenOpts.DwarfVersion) { getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version", CodeGenOpts.DwarfVersion); @@ -4781,6 +4782,10 @@ CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, } } setDSOLocal(F); + // FIXME: We should use CodeGenModule::SetLLVMFunctionAttributes() instead + // of trying to approximate the attributes using the LLVM function + // signature. This requires revising the API of CreateRuntimeFunction(). + markRegisterParameterAttributes(F); } } diff --git a/clang/lib/CodeGen/MicrosoftCXXABI.cpp b/clang/lib/CodeGen/MicrosoftCXXABI.cpp index d38a26940a3cb613a29557019f92b60b49cb7a9e..d47927745759e1406d0b97cb6cd34d5b05a6ddf6 100644 --- a/clang/lib/CodeGen/MicrosoftCXXABI.cpp +++ b/clang/lib/CodeGen/MicrosoftCXXABI.cpp @@ -1131,9 +1131,15 @@ static bool isTrivialForMSVC(const CXXRecordDecl *RD, QualType Ty, return false; if (RD->hasNonTrivialCopyAssignment()) return false; - for (const CXXConstructorDecl *Ctor : RD->ctors()) - if (Ctor->isUserProvided()) - return false; + for (const Decl *D : RD->decls()) { + if (auto *Ctor = dyn_cast(D)) { + if (Ctor->isUserProvided()) + return false; + } else if (auto *Template = dyn_cast(D)) { + if (isa(Template->getTemplatedDecl())) + return false; + } + } if (RD->hasNonTrivialDestructor()) return false; return true; diff --git a/clang/lib/Driver/CMakeLists.txt b/clang/lib/Driver/CMakeLists.txt index 58427e3f83c4201f4b6e7b996c5175aa1ffc2638..32a4378ab499fafb9a95cb8f740586d8798c32db 100644 --- a/clang/lib/Driver/CMakeLists.txt +++ b/clang/lib/Driver/CMakeLists.txt @@ -90,6 +90,9 @@ add_clang_library(clangDriver DEPENDS ClangDriverOptions + # These generated headers are included transitively. + ARMTargetParserTableGen + AArch64TargetParserTableGen LINK_LIBS clangBasic diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp index 76b7b9fdfb4f9b0cc8a82c1f69d534443b483fcc..114320f5d314681ebef32466078da47dc4f8e235 100644 --- a/clang/lib/Driver/Driver.cpp +++ b/clang/lib/Driver/Driver.cpp @@ -361,6 +361,7 @@ phases::ID Driver::getFinalPhase(const DerivedArgList &DAL, (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) || (PhaseArg = DAL.getLastArg(options::OPT__migrate)) || (PhaseArg = DAL.getLastArg(options::OPT__analyze)) || + (PhaseArg = DAL.getLastArg(options::OPT_emit_cir)) || (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) { FinalPhase = phases::Compile; @@ -4799,6 +4800,8 @@ Action *Driver::ConstructPhaseAction( return C.MakeAction(Input, types::TY_Remap); if (Args.hasArg(options::OPT_emit_ast)) return C.MakeAction(Input, types::TY_AST); + if (Args.hasArg(options::OPT_emit_cir)) + return C.MakeAction(Input, types::TY_CIR); if (Args.hasArg(options::OPT_module_file_info)) return C.MakeAction(Input, types::TY_ModuleFile); if (Args.hasArg(options::OPT_verify_pch)) diff --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp index 341d6202a9ca3c69c608097d1497b5bf63fcb75d..0e86bc07e0ea2c5d5265bc0a1422f535e70d0449 100644 --- a/clang/lib/Driver/ToolChain.cpp +++ b/clang/lib/Driver/ToolChain.cpp @@ -1316,14 +1316,19 @@ bool ToolChain::isFastMathRuntimeAvailable(const ArgList &Args, // (to keep the linker options consistent with gcc and clang itself). if (Default && !isOptimizationLevelFast(Args)) { // Check if -ffast-math or -funsafe-math. - Arg *A = - Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math, - options::OPT_funsafe_math_optimizations, - options::OPT_fno_unsafe_math_optimizations); + Arg *A = Args.getLastArg( + options::OPT_ffast_math, options::OPT_fno_fast_math, + options::OPT_funsafe_math_optimizations, + options::OPT_fno_unsafe_math_optimizations, options::OPT_ffp_model_EQ); if (!A || A->getOption().getID() == options::OPT_fno_fast_math || A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations) Default = false; + if (A && A->getOption().getID() == options::OPT_ffp_model_EQ) { + StringRef Model = A->getValue(); + if (Model != "fast") + Default = false; + } } // Whatever decision came as a result of the above implicit settings, either diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp index f4fe7422cba6303a23c77bcc54998c62979bf858..1f08c5958dfb60e65bdd46f8af4a8e33fc08982c 100644 --- a/clang/lib/Driver/ToolChains/Clang.cpp +++ b/clang/lib/Driver/ToolChains/Clang.cpp @@ -2743,13 +2743,11 @@ static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D, StringRef FPExceptionBehavior = ""; // -ffp-eval-method options: double, extended, source StringRef FPEvalMethod = ""; - const llvm::DenormalMode DefaultDenormalFPMath = + llvm::DenormalMode DenormalFPMath = TC.getDefaultDenormalModeForType(Args, JA); - const llvm::DenormalMode DefaultDenormalFP32Math = + llvm::DenormalMode DenormalFP32Math = TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle()); - llvm::DenormalMode DenormalFPMath = DefaultDenormalFPMath; - llvm::DenormalMode DenormalFP32Math = DefaultDenormalFP32Math; // CUDA and HIP don't rely on the frontend to pass an ffp-contract option. // If one wasn't given by the user, don't pass it here. StringRef FPContract; @@ -2899,11 +2897,6 @@ static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D, SignedZeros = true; // -fno_fast_math restores default denormal and fpcontract handling FPContract = "on"; - DenormalFPMath = llvm::DenormalMode::getIEEE(); - - // FIXME: The target may have picked a non-IEEE default mode here based on - // -cl-denorms-are-zero. Should the target consider -fp-model interaction? - DenormalFP32Math = llvm::DenormalMode::getIEEE(); StringRef Val = A->getValue(); if (OFastEnabled && !Val.equals("fast")) { @@ -3119,12 +3112,7 @@ static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D, ReciprocalMath = false; SignedZeros = true; ApproxFunc = false; - TrappingMath = true; - FPExceptionBehavior = "strict"; - // The target may have opted to flush by default, so force IEEE. - DenormalFPMath = llvm::DenormalMode::getIEEE(); - DenormalFP32Math = llvm::DenormalMode::getIEEE(); if (!JA.isDeviceOffloading(Action::OFK_Cuda) && !JA.isOffloading(Action::OFK_HIP)) { if (LastSeenFfpContractOption != "") { @@ -3154,9 +3142,7 @@ static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D, ReciprocalMath = false; ApproxFunc = false; SignedZeros = true; - // -fno_fast_math restores default denormal and fpcontract handling - DenormalFPMath = DefaultDenormalFPMath; - DenormalFP32Math = llvm::DenormalMode::getIEEE(); + // -fno_fast_math restores default fpcontract handling if (!JA.isDeviceOffloading(Action::OFK_Cuda) && !JA.isOffloading(Action::OFK_HIP)) { if (LastSeenFfpContractOption != "") { @@ -3171,8 +3157,6 @@ static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D, // subsequent options conflict then emit warning diagnostic. if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath && SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc && - DenormalFPMath == llvm::DenormalMode::getIEEE() && - DenormalFP32Math == llvm::DenormalMode::getIEEE() && FPContract.equals("off")) // OK: Current Arg doesn't conflict with -ffp-model=strict ; @@ -7262,15 +7246,10 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, Args.addOptInFlag(CmdArgs, options::OPT_frelaxed_template_template_args, options::OPT_fno_relaxed_template_template_args); - // -fsized-deallocation is on by default in C++14 onwards and otherwise off - // by default. - if (Arg *A = Args.getLastArg(options::OPT_fsized_deallocation, - options::OPT_fno_sized_deallocation)) { - if (A->getOption().matches(options::OPT_fno_sized_deallocation)) - CmdArgs.push_back("-fno-sized-deallocation"); - else - CmdArgs.push_back("-fsized-deallocation"); - } + // -fsized-deallocation is off by default, as it is an ABI-breaking change for + // most platforms. + Args.addOptInFlag(CmdArgs, options::OPT_fsized_deallocation, + options::OPT_fno_sized_deallocation); // -faligned-allocation is on by default in C++17 onwards and otherwise off // by default. @@ -7509,6 +7488,9 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, Args.addOptInFlag(CmdArgs, options::OPT_fsafe_buffer_usage_suggestions, options::OPT_fno_safe_buffer_usage_suggestions); + Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_late_parse_attributes, + options::OPT_fno_experimental_late_parse_attributes); + // Setup statistics file output. SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D); if (!StatsFile.empty()) { diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp b/clang/lib/Driver/ToolChains/CommonArgs.cpp index b65b96db16bd79583dc6dd4857f27c111ee0fb88..6796b43a155020fe27982243ba03081eba4751c2 100644 --- a/clang/lib/Driver/ToolChains/CommonArgs.cpp +++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp @@ -737,7 +737,7 @@ bool tools::isTLSDESCEnabled(const ToolChain &TC, StringRef V = A->getValue(); bool SupportedArgument = false, EnableTLSDESC = false; bool Unsupported = !Triple.isOSBinFormatELF(); - if (Triple.isRISCV()) { + if (Triple.isLoongArch() || Triple.isRISCV()) { SupportedArgument = V == "desc" || V == "trad"; EnableTLSDESC = V == "desc"; } else if (Triple.isX86()) { @@ -1191,118 +1191,10 @@ bool tools::addOpenMPRuntime(const Compilation &C, ArgStringList &CmdArgs, return true; } -/// Determines if --whole-archive is active in the list of arguments. -static bool isWholeArchivePresent(const ArgList &Args) { - bool WholeArchiveActive = false; - for (auto *Arg : Args.filtered(options::OPT_Wl_COMMA)) { - if (Arg) { - for (StringRef ArgValue : Arg->getValues()) { - if (ArgValue == "--whole-archive") - WholeArchiveActive = true; - if (ArgValue == "--no-whole-archive") - WholeArchiveActive = false; - } - } - } - - return WholeArchiveActive; -} - -/// Determine if driver is invoked to create a shared object library (-static) -static bool isSharedLinkage(const ArgList &Args) { - return Args.hasArg(options::OPT_shared); -} - -/// Determine if driver is invoked to create a static object library (-shared) -static bool isStaticLinkage(const ArgList &Args) { - return Args.hasArg(options::OPT_static); -} - -/// Add Fortran runtime libs for MSVC -static void addFortranRuntimeLibsMSVC(const ArgList &Args, - llvm::opt::ArgStringList &CmdArgs) { - unsigned RTOptionID = options::OPT__SLASH_MT; - if (auto *rtl = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) { - RTOptionID = llvm::StringSwitch(rtl->getValue()) - .Case("static", options::OPT__SLASH_MT) - .Case("static_dbg", options::OPT__SLASH_MTd) - .Case("dll", options::OPT__SLASH_MD) - .Case("dll_dbg", options::OPT__SLASH_MDd) - .Default(options::OPT__SLASH_MT); - } - switch (RTOptionID) { - case options::OPT__SLASH_MT: - CmdArgs.push_back("/WHOLEARCHIVE:Fortran_main.static.lib"); - break; - case options::OPT__SLASH_MTd: - CmdArgs.push_back("/WHOLEARCHIVE:Fortran_main.static_dbg.lib"); - break; - case options::OPT__SLASH_MD: - CmdArgs.push_back("/WHOLEARCHIVE:Fortran_main.dynamic.lib"); - break; - case options::OPT__SLASH_MDd: - CmdArgs.push_back("/WHOLEARCHIVE:Fortran_main.dynamic_dbg.lib"); - break; - } -} - -// Add FortranMain runtime lib -static void addFortranMain(const ToolChain &TC, const ArgList &Args, - llvm::opt::ArgStringList &CmdArgs) { - // 0. Shared-library linkage - // If we are attempting to link a library, we should not add - // -lFortran_main.a to the link line, as the `main` symbol is not - // required for a library and should also be provided by one of - // the translation units of the code that this shared library - // will be linked against eventually. - if (isSharedLinkage(Args) || isStaticLinkage(Args)) { - return; - } - - // 1. MSVC - if (TC.getTriple().isKnownWindowsMSVCEnvironment()) { - addFortranRuntimeLibsMSVC(Args, CmdArgs); - return; - } - - // 2. GNU and similar - const Driver &D = TC.getDriver(); - const char *FortranMainLinkFlag = "-lFortran_main"; - - // Warn if the user added `-lFortran_main` - this library is an implementation - // detail of Flang and should be handled automaticaly by the driver. - for (const char *arg : CmdArgs) { - if (strncmp(arg, FortranMainLinkFlag, strlen(FortranMainLinkFlag)) == 0) - D.Diag(diag::warn_drv_deprecated_custom) - << FortranMainLinkFlag - << "see the Flang driver documentation for correct usage"; - } - - // The --whole-archive option needs to be part of the link line to make - // sure that the main() function from Fortran_main.a is pulled in by the - // linker. However, it shouldn't be used if it's already active. - // TODO: Find an equivalent of `--whole-archive` for Darwin and AIX. - if (!isWholeArchivePresent(Args) && !TC.getTriple().isMacOSX() && - !TC.getTriple().isOSAIX()) { - CmdArgs.push_back("--whole-archive"); - CmdArgs.push_back(FortranMainLinkFlag); - CmdArgs.push_back("--no-whole-archive"); - return; - } - - CmdArgs.push_back(FortranMainLinkFlag); -} - /// Add Fortran runtime libs void tools::addFortranRuntimeLibs(const ToolChain &TC, const ArgList &Args, llvm::opt::ArgStringList &CmdArgs) { - // 1. Link FortranMain - // FortranMain depends on FortranRuntime, so needs to be listed first. If - // -fno-fortran-main has been passed, skip linking Fortran_main.a - if (!Args.hasArg(options::OPT_no_fortran_main)) - addFortranMain(TC, Args, CmdArgs); - - // 2. Link FortranRuntime and FortranDecimal + // Link FortranRuntime and FortranDecimal // These are handled earlier on Windows by telling the frontend driver to // add the correct libraries to link against as dependents in the object // file. diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp b/clang/lib/Driver/ToolChains/Darwin.cpp index 593b403a1e3f057e82c5f7ce42f9963c1057f228..caf6c4a444fdcec76007c09ffc73c15bc4d3002c 100644 --- a/clang/lib/Driver/ToolChains/Darwin.cpp +++ b/clang/lib/Driver/ToolChains/Darwin.cpp @@ -2912,54 +2912,9 @@ static bool sdkSupportsBuiltinModules(const Darwin::DarwinPlatformKind &TargetPl } } -static inline llvm::VersionTuple -sizedDeallocMinVersion(llvm::Triple::OSType OS) { - switch (OS) { - default: - break; - case llvm::Triple::Darwin: - case llvm::Triple::MacOSX: // Earliest supporting version is 10.12. - return llvm::VersionTuple(10U, 12U); - case llvm::Triple::IOS: - case llvm::Triple::TvOS: // Earliest supporting version is 10.0.0. - return llvm::VersionTuple(10U); - case llvm::Triple::WatchOS: // Earliest supporting version is 3.0.0. - return llvm::VersionTuple(3U); - } - - llvm_unreachable("Unexpected OS"); -} - -bool Darwin::isSizedDeallocationUnavailable() const { - llvm::Triple::OSType OS; - - if (isTargetMacCatalyst()) - return TargetVersion < sizedDeallocMinVersion(llvm::Triple::MacOSX); - switch (TargetPlatform) { - case MacOS: // Earlier than 10.12. - OS = llvm::Triple::MacOSX; - break; - case IPhoneOS: - OS = llvm::Triple::IOS; - break; - case TvOS: // Earlier than 10.0. - OS = llvm::Triple::TvOS; - break; - case WatchOS: // Earlier than 3.0. - OS = llvm::Triple::WatchOS; - break; - case DriverKit: - case XROS: - // Always available. - return false; - } - - return TargetVersion < sizedDeallocMinVersion(OS); -} - -void Darwin::addClangTargetOptions( - const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, - Action::OffloadKind DeviceOffloadKind) const { +void Darwin::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, + llvm::opt::ArgStringList &CC1Args, + Action::OffloadKind DeviceOffloadKind) const { // Pass "-faligned-alloc-unavailable" only when the user hasn't manually // enabled or disabled aligned allocations. if (!DriverArgs.hasArgNoClaim(options::OPT_faligned_allocation, @@ -2967,13 +2922,6 @@ void Darwin::addClangTargetOptions( isAlignedAllocationUnavailable()) CC1Args.push_back("-faligned-alloc-unavailable"); - // Pass "-fno-sized-deallocation" only when the user hasn't manually enabled - // or disabled sized deallocations. - if (!DriverArgs.hasArgNoClaim(options::OPT_fsized_deallocation, - options::OPT_fno_sized_deallocation) && - isSizedDeallocationUnavailable()) - CC1Args.push_back("-fno-sized-deallocation"); - addClangCC1ASTargetOptions(DriverArgs, CC1Args); // Enable compatibility mode for NSItemProviderCompletionHandler in diff --git a/clang/lib/Driver/ToolChains/Darwin.h b/clang/lib/Driver/ToolChains/Darwin.h index b45279ecedeb250af0c123007745221e17509e7d..10d4b69e5d5f10dacd40442f20930ca0aeca719f 100644 --- a/clang/lib/Driver/ToolChains/Darwin.h +++ b/clang/lib/Driver/ToolChains/Darwin.h @@ -511,10 +511,6 @@ protected: /// targeting. bool isAlignedAllocationUnavailable() const; - /// Return true if c++14 sized deallocation functions are not implemented in - /// the c++ standard library of the deployment target we are targeting. - bool isSizedDeallocationUnavailable() const; - void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, Action::OffloadKind DeviceOffloadKind) const override; diff --git a/clang/lib/Driver/ToolChains/Flang.cpp b/clang/lib/Driver/ToolChains/Flang.cpp index 6d93c1f3d7034a02dd8beed312e7b0457ba67bd6..8955b9fb653c2acc5a4a7708d430a8aa976dca79 100644 --- a/clang/lib/Driver/ToolChains/Flang.cpp +++ b/clang/lib/Driver/ToolChains/Flang.cpp @@ -282,7 +282,6 @@ static void processVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args, assert(TC.getTriple().isKnownWindowsMSVCEnvironment() && "can only add VS runtime library on Windows!"); // if -fno-fortran-main has been passed, skip linking Fortran_main.a - bool LinkFortranMain = !Args.hasArg(options::OPT_no_fortran_main); if (TC.getTriple().isKnownWindowsMSVCEnvironment()) { CmdArgs.push_back(Args.MakeArgString( "--dependent-lib=" + TC.getCompilerRTBasename(Args, "builtins"))); @@ -300,8 +299,6 @@ static void processVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args, case options::OPT__SLASH_MT: CmdArgs.push_back("-D_MT"); CmdArgs.push_back("--dependent-lib=libcmt"); - if (LinkFortranMain) - CmdArgs.push_back("--dependent-lib=Fortran_main.static.lib"); CmdArgs.push_back("--dependent-lib=FortranRuntime.static.lib"); CmdArgs.push_back("--dependent-lib=FortranDecimal.static.lib"); break; @@ -309,8 +306,6 @@ static void processVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args, CmdArgs.push_back("-D_MT"); CmdArgs.push_back("-D_DEBUG"); CmdArgs.push_back("--dependent-lib=libcmtd"); - if (LinkFortranMain) - CmdArgs.push_back("--dependent-lib=Fortran_main.static_dbg.lib"); CmdArgs.push_back("--dependent-lib=FortranRuntime.static_dbg.lib"); CmdArgs.push_back("--dependent-lib=FortranDecimal.static_dbg.lib"); break; @@ -318,8 +313,6 @@ static void processVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args, CmdArgs.push_back("-D_MT"); CmdArgs.push_back("-D_DLL"); CmdArgs.push_back("--dependent-lib=msvcrt"); - if (LinkFortranMain) - CmdArgs.push_back("--dependent-lib=Fortran_main.dynamic.lib"); CmdArgs.push_back("--dependent-lib=FortranRuntime.dynamic.lib"); CmdArgs.push_back("--dependent-lib=FortranDecimal.dynamic.lib"); break; @@ -328,8 +321,6 @@ static void processVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args, CmdArgs.push_back("-D_DEBUG"); CmdArgs.push_back("-D_DLL"); CmdArgs.push_back("--dependent-lib=msvcrtd"); - if (LinkFortranMain) - CmdArgs.push_back("--dependent-lib=Fortran_main.dynamic_dbg.lib"); CmdArgs.push_back("--dependent-lib=FortranRuntime.dynamic_dbg.lib"); CmdArgs.push_back("--dependent-lib=FortranDecimal.dynamic_dbg.lib"); break; diff --git a/clang/lib/Driver/ToolChains/Gnu.cpp b/clang/lib/Driver/ToolChains/Gnu.cpp index f55b8bf48c13f781a69eaf464b60123618bd022b..9849c59685cca78b6e1645ed7aa3d8a05cd9f182 100644 --- a/clang/lib/Driver/ToolChains/Gnu.cpp +++ b/clang/lib/Driver/ToolChains/Gnu.cpp @@ -1796,9 +1796,7 @@ selectRISCVMultilib(const MultilibSet &RISCVMultilibSet, StringRef Arch, } auto &MLConfigISAInfo = *MLConfigParseResult; - const llvm::RISCVISAInfo::OrderedExtensionMap &MLConfigArchExts = - MLConfigISAInfo->getExtensions(); - for (auto MLConfigArchExt : MLConfigArchExts) { + for (auto &MLConfigArchExt : MLConfigISAInfo->getExtensions()) { auto ExtName = MLConfigArchExt.first; NewMultilib.flag(Twine("-", ExtName).str()); diff --git a/clang/lib/Driver/ToolChains/ZOS.cpp b/clang/lib/Driver/ToolChains/ZOS.cpp index 074e0556ecd2ad2a60bba85539ad58bcd1d49965..d5fc7b8ef562a66870c15838cbd2ff60d90127a7 100644 --- a/clang/lib/Driver/ToolChains/ZOS.cpp +++ b/clang/lib/Driver/ToolChains/ZOS.cpp @@ -36,12 +36,6 @@ void ZOS::addClangTargetOptions(const ArgList &DriverArgs, if (!DriverArgs.hasArgNoClaim(options::OPT_faligned_allocation, options::OPT_fno_aligned_allocation)) CC1Args.push_back("-faligned-alloc-unavailable"); - - // Pass "-fno-sized-deallocation" only when the user hasn't manually enabled - // or disabled sized deallocations. - if (!DriverArgs.hasArgNoClaim(options::OPT_fsized_deallocation, - options::OPT_fno_sized_deallocation)) - CC1Args.push_back("-fno-sized-deallocation"); } void zos::Assembler::ConstructJob(Compilation &C, const JobAction &JA, diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h index f651e6228c206da58363e5d7482e108001cba788..28b6488e54a4223c03dde637ee246db7c6e0cdc9 100644 --- a/clang/lib/Format/FormatToken.h +++ b/clang/lib/Format/FormatToken.h @@ -1623,10 +1623,10 @@ struct AdditionalKeywords { IdentifierInfo *kw_then; /// Returns \c true if \p Tok is a keyword or an identifier. - bool isWordLike(const FormatToken &Tok) const { + bool isWordLike(const FormatToken &Tok, bool IsVerilog = true) const { // getIdentifierinfo returns non-null for keywords as well as identifiers. return Tok.Tok.getIdentifierInfo() && - !Tok.isOneOf(kw_verilogHash, kw_verilogHashHash, kw_apostrophe); + (!IsVerilog || !isVerilogKeywordSymbol(Tok)); } /// Returns \c true if \p Tok is a true JavaScript identifier, returns @@ -1755,6 +1755,10 @@ struct AdditionalKeywords { } } + bool isVerilogKeywordSymbol(const FormatToken &Tok) const { + return Tok.isOneOf(kw_verilogHash, kw_verilogHashHash, kw_apostrophe); + } + bool isVerilogWordOperator(const FormatToken &Tok) const { return Tok.isOneOf(kw_before, kw_intersect, kw_dist, kw_iff, kw_inside, kw_with); diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index cdfb4256e41d93ddf36de11fb047aeb4fdc37eb0..d366ae2080bc25eebff64e74b9fd06db1433be5c 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -4780,9 +4780,14 @@ bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line, if (Left.Finalized) return Right.hasWhitespaceBefore(); + const bool IsVerilog = Style.isVerilog(); + assert(!IsVerilog || !IsCpp); + // Never ever merge two words. - if (Keywords.isWordLike(Right) && Keywords.isWordLike(Left)) + if (Keywords.isWordLike(Right, IsVerilog) && + Keywords.isWordLike(Left, IsVerilog)) { return true; + } // Leave a space between * and /* to avoid C4138 `comment end` found outside // of comment. @@ -4834,10 +4839,8 @@ bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line, Right.is(TT_TemplateOpener)) { return true; } - if (Left.is(tok::identifier) && Right.is(tok::numeric_constant) && - Right.TokenText[0] == '.') { - return false; - } + if (Left.Tok.getIdentifierInfo() && Right.is(tok::numeric_constant)) + return Right.TokenText[0] != '.'; } else if (Style.isProto()) { if (Right.is(tok::period) && Left.isOneOf(Keywords.kw_optional, Keywords.kw_required, @@ -5065,12 +5068,10 @@ bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line, Right.is(TT_TemplateOpener)) { return true; } - } else if (Style.isVerilog()) { + } else if (IsVerilog) { // An escaped identifier ends with whitespace. - if (Style.isVerilog() && Left.is(tok::identifier) && - Left.TokenText[0] == '\\') { + if (Left.is(tok::identifier) && Left.TokenText[0] == '\\') return true; - } // Add space between things in a primitive's state table unless in a // transition like `(0?)`. if ((Left.is(TT_VerilogTableItem) && @@ -5266,21 +5267,11 @@ bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line, return true; } if (Left.is(TT_UnaryOperator)) { - if (Right.isNot(tok::l_paren)) { - // The alternative operators for ~ and ! are "compl" and "not". - // If they are used instead, we do not want to combine them with - // the token to the right, unless that is a left paren. - if (Left.is(tok::exclaim) && Left.TokenText == "not") - return true; - if (Left.is(tok::tilde) && Left.TokenText == "compl") - return true; - // Lambda captures allow for a lone &, so "&]" needs to be properly - // handled. - if (Left.is(tok::amp) && Right.is(tok::r_square)) - return Style.SpacesInSquareBrackets; - } - return (Style.SpaceAfterLogicalNot && Left.is(tok::exclaim)) || - Right.is(TT_BinaryOperator); + // Lambda captures allow for a lone &, so "&]" needs to be properly + // handled. + if (Left.is(tok::amp) && Right.is(tok::r_square)) + return Style.SpacesInSquareBrackets; + return Style.SpaceAfterLogicalNot && Left.is(tok::exclaim); } // If the next token is a binary operator or a selector name, we have diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index 3a263955a6a8fef805a83e48ce8b77672fb32b0e..854428389740d89629ab62e6749a5b8e04612651 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -3944,8 +3944,11 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) { switch (FormatTok->Tok.getKind()) { case tok::l_paren: // We can have macros in between 'class' and the class name. - if (!IsNonMacroIdentifier(Previous)) + if (!IsNonMacroIdentifier(Previous) || + // e.g. `struct macro(a) S { int i; };` + Previous->Previous == &InitialToken) { parseParens(); + } break; case tok::coloncolon: break; diff --git a/clang/lib/Format/WhitespaceManager.cpp b/clang/lib/Format/WhitespaceManager.cpp index 4f822807dd987dc8ceeb43e8a550c4c135f50b86..44fd807ec27ea75450754dc38c85330ab3aed4a0 100644 --- a/clang/lib/Format/WhitespaceManager.cpp +++ b/clang/lib/Format/WhitespaceManager.cpp @@ -128,11 +128,14 @@ const tooling::Replacements &WhitespaceManager::generateReplacements() { void WhitespaceManager::calculateLineBreakInformation() { Changes[0].PreviousEndOfTokenColumn = 0; Change *LastOutsideTokenChange = &Changes[0]; - for (unsigned i = 1, e = Changes.size(); i != e; ++i) { + for (unsigned I = 1, e = Changes.size(); I != e; ++I) { + auto &C = Changes[I]; + auto &P = Changes[I - 1]; + auto &PrevTokLength = P.TokenLength; SourceLocation OriginalWhitespaceStart = - Changes[i].OriginalWhitespaceRange.getBegin(); + C.OriginalWhitespaceRange.getBegin(); SourceLocation PreviousOriginalWhitespaceEnd = - Changes[i - 1].OriginalWhitespaceRange.getEnd(); + P.OriginalWhitespaceRange.getEnd(); unsigned OriginalWhitespaceStartOffset = SourceMgr.getFileOffset(OriginalWhitespaceStart); unsigned PreviousOriginalWhitespaceEndOffset = @@ -167,31 +170,28 @@ void WhitespaceManager::calculateLineBreakInformation() { // line of the token. auto NewlinePos = Text.find_first_of('\n'); if (NewlinePos == StringRef::npos) { - Changes[i - 1].TokenLength = OriginalWhitespaceStartOffset - - PreviousOriginalWhitespaceEndOffset + - Changes[i].PreviousLinePostfix.size() + - Changes[i - 1].CurrentLinePrefix.size(); + PrevTokLength = OriginalWhitespaceStartOffset - + PreviousOriginalWhitespaceEndOffset + + C.PreviousLinePostfix.size() + P.CurrentLinePrefix.size(); + if (!P.IsInsideToken) + PrevTokLength = std::min(PrevTokLength, P.Tok->ColumnWidth); } else { - Changes[i - 1].TokenLength = - NewlinePos + Changes[i - 1].CurrentLinePrefix.size(); + PrevTokLength = NewlinePos + P.CurrentLinePrefix.size(); } // If there are multiple changes in this token, sum up all the changes until // the end of the line. - if (Changes[i - 1].IsInsideToken && Changes[i - 1].NewlinesBefore == 0) { - LastOutsideTokenChange->TokenLength += - Changes[i - 1].TokenLength + Changes[i - 1].Spaces; - } else { - LastOutsideTokenChange = &Changes[i - 1]; - } + if (P.IsInsideToken && P.NewlinesBefore == 0) + LastOutsideTokenChange->TokenLength += PrevTokLength + P.Spaces; + else + LastOutsideTokenChange = &P; - Changes[i].PreviousEndOfTokenColumn = - Changes[i - 1].StartOfTokenColumn + Changes[i - 1].TokenLength; + C.PreviousEndOfTokenColumn = P.StartOfTokenColumn + PrevTokLength; - Changes[i - 1].IsTrailingComment = - (Changes[i].NewlinesBefore > 0 || Changes[i].Tok->is(tok::eof) || - (Changes[i].IsInsideToken && Changes[i].Tok->is(tok::comment))) && - Changes[i - 1].Tok->is(tok::comment) && + P.IsTrailingComment = + (C.NewlinesBefore > 0 || C.Tok->is(tok::eof) || + (C.IsInsideToken && C.Tok->is(tok::comment))) && + P.Tok->is(tok::comment) && // FIXME: This is a dirty hack. The problem is that // BreakableLineCommentSection does comment reflow changes and here is // the aligning of trailing comments. Consider the case where we reflow diff --git a/clang/lib/Frontend/CompilerInvocation.cpp b/clang/lib/Frontend/CompilerInvocation.cpp index 8236051e30c4a5daa74b8ae09ce7e77d286cfad9..8312abc3603953e90f5334854cfbde1f5c0e2822 100644 --- a/clang/lib/Frontend/CompilerInvocation.cpp +++ b/clang/lib/Frontend/CompilerInvocation.cpp @@ -2549,6 +2549,7 @@ static const auto &getFrontendActionTable() { {frontend::DumpTokens, OPT_dump_tokens}, {frontend::EmitAssembly, OPT_S}, {frontend::EmitBC, OPT_emit_llvm_bc}, + {frontend::EmitCIR, OPT_emit_cir}, {frontend::EmitHTML, OPT_emit_html}, {frontend::EmitLLVM, OPT_emit_llvm}, {frontend::EmitLLVMOnly, OPT_emit_llvm_only}, @@ -2891,6 +2892,8 @@ static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, if (Opts.ProgramAction != frontend::GenerateModule && Opts.IsSystemModule) Diags.Report(diag::err_drv_argument_only_allowed_with) << "-fsystem-module" << "-emit-module"; + if (Args.hasArg(OPT_fclangir) || Args.hasArg(OPT_emit_cir)) + Opts.UseClangIRPipeline = true; if (Args.hasArg(OPT_aux_target_cpu)) Opts.AuxTargetCPU = std::string(Args.getLastArgValue(OPT_aux_target_cpu)); @@ -4337,6 +4340,7 @@ static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) { case frontend::ASTView: case frontend::EmitAssembly: case frontend::EmitBC: + case frontend::EmitCIR: case frontend::EmitHTML: case frontend::EmitLLVM: case frontend::EmitLLVMOnly: diff --git a/clang/lib/Frontend/FrontendActions.cpp b/clang/lib/Frontend/FrontendActions.cpp index 04eb104132671357f84a8d74b070636bff90087e..454653a31534cd3ef7d22d2dbf51aed94314b547 100644 --- a/clang/lib/Frontend/FrontendActions.cpp +++ b/clang/lib/Frontend/FrontendActions.cpp @@ -272,14 +272,10 @@ bool GenerateModuleInterfaceAction::BeginSourceFileAction( std::unique_ptr GenerateModuleInterfaceAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { - CI.getHeaderSearchOpts().ModulesSkipDiagnosticOptions = true; - CI.getHeaderSearchOpts().ModulesSkipHeaderSearchPaths = true; - CI.getHeaderSearchOpts().ModulesSkipPragmaDiagnosticMappings = true; - - std::vector> Consumers = - CreateMultiplexConsumer(CI, InFile); - if (Consumers.empty()) - return nullptr; + std::vector> Consumers; + Consumers.push_back(std::make_unique( + CI.getPreprocessor(), CI.getModuleCache(), + CI.getFrontendOpts().OutputFile)); if (CI.getFrontendOpts().GenReducedBMI && !CI.getFrontendOpts().ModuleOutputPath.empty()) { diff --git a/clang/lib/Frontend/InitPreprocessor.cpp b/clang/lib/Frontend/InitPreprocessor.cpp index 745d1a5aca55b988cb539b02cf66f7931d2ac9ca..c1d209466ffe5dd34edc5ab5f703f2656f88b92a 100644 --- a/clang/lib/Frontend/InitPreprocessor.cpp +++ b/clang/lib/Frontend/InitPreprocessor.cpp @@ -703,7 +703,7 @@ static void InitializeCPlusPlusFeatureTestMacros(const LangOptions &LangOpts, Builder.defineMacro("__cpp_nested_namespace_definitions", "201411L"); Builder.defineMacro("__cpp_variadic_using", "201611L"); Builder.defineMacro("__cpp_aggregate_bases", "201603L"); - Builder.defineMacro("__cpp_structured_bindings", "201606L"); + Builder.defineMacro("__cpp_structured_bindings", "202403L"); Builder.defineMacro("__cpp_nontype_template_args", "201411L"); // (not latest) Builder.defineMacro("__cpp_fold_expressions", "201603L"); diff --git a/clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp b/clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp index f85f0365616f9ad8a92805a753bbc385aaa7a304..7476b1076d10381df8f485ffc3a05573ad68c9ee 100644 --- a/clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp +++ b/clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp @@ -53,6 +53,8 @@ CreateFrontendBaseAction(CompilerInstance &CI) { case DumpTokens: return std::make_unique(); case EmitAssembly: return std::make_unique(); case EmitBC: return std::make_unique(); + case EmitCIR: + llvm_unreachable("CIR suppport not built into clang"); case EmitHTML: return std::make_unique(); case EmitLLVM: return std::make_unique(); case EmitLLVMOnly: return std::make_unique(); diff --git a/clang/lib/Headers/CMakeLists.txt b/clang/lib/Headers/CMakeLists.txt index e6ae4e19e81db9c13b2aeb040714c747c9953e56..3416811e39de2702930dfad2222a97e1969ed488 100644 --- a/clang/lib/Headers/CMakeLists.txt +++ b/clang/lib/Headers/CMakeLists.txt @@ -335,6 +335,10 @@ set(llvm_libc_wrapper_files llvm_libc_wrappers/time.h ) +set(zos_wrapper_files + zos_wrappers/builtins.h +) + include(GetClangResourceDir) get_clang_resource_dir(output_dir PREFIX ${LLVM_LIBRARY_OUTPUT_INTDIR}/.. SUBDIR include) set(out_files) @@ -370,7 +374,7 @@ endfunction(clang_generate_header) # Copy header files from the source directory to the build directory foreach( f ${files} ${cuda_wrapper_files} ${cuda_wrapper_bits_files} - ${ppc_wrapper_files} ${openmp_wrapper_files} ${hlsl_files} + ${ppc_wrapper_files} ${openmp_wrapper_files} ${zos_wrapper_files} ${hlsl_files} ${llvm_libc_wrapper_files}) copy_header_to_output_dir(${CMAKE_CURRENT_SOURCE_DIR} ${f}) endforeach( f ) @@ -487,7 +491,7 @@ add_header_target("mips-resource-headers" "${mips_msa_files}") add_header_target("ppc-resource-headers" "${ppc_files};${ppc_wrapper_files}") add_header_target("ppc-htm-resource-headers" "${ppc_htm_files}") add_header_target("riscv-resource-headers" "${riscv_files};${riscv_generated_files}") -add_header_target("systemz-resource-headers" "${systemz_files}") +add_header_target("systemz-resource-headers" "${systemz_files};${zos_wrapper_files}") add_header_target("ve-resource-headers" "${ve_files}") add_header_target("webassembly-resource-headers" "${webassembly_files}") add_header_target("x86-resource-headers" "${x86_files}") @@ -538,6 +542,11 @@ install( DESTINATION ${header_install_dir}/openmp_wrappers COMPONENT clang-resource-headers) +install( + FILES ${zos_wrapper_files} + DESTINATION ${header_install_dir}/zos_wrappers + COMPONENT clang-resource-headers) + ############################################################# # Install rules for separate header lists install( @@ -642,6 +651,12 @@ install( EXCLUDE_FROM_ALL COMPONENT systemz-resource-headers) +install( + FILES ${zos_wrapper_files} + DESTINATION ${header_install_dir}/zos_wrappers + EXCLUDE_FROM_ALL + COMPONENT systemz-resource-headers) + install( FILES ${ve_files} DESTINATION ${header_install_dir} diff --git a/clang/lib/Headers/builtins.h b/clang/lib/Headers/builtins.h index 65095861ca9b1c57f214d5d08ac7cc5b9637a8fc..1e534e632c8ead3ca6f515ba4d44ff858833efc0 100644 --- a/clang/lib/Headers/builtins.h +++ b/clang/lib/Headers/builtins.h @@ -13,4 +13,7 @@ #ifndef __BUILTINS_H #define __BUILTINS_H +#if defined(__MVS__) && __has_include_next() +#include_next +#endif /* __MVS__ */ #endif /* __BUILTINS_H */ diff --git a/clang/lib/Headers/float.h b/clang/lib/Headers/float.h index 0e73bca0a2d6e4c9d2d9ccdb1c0b17f2114f5fb0..642c8f06cc9386362cb4eb40c4eb7d5a31642235 100644 --- a/clang/lib/Headers/float.h +++ b/clang/lib/Headers/float.h @@ -10,6 +10,10 @@ #ifndef __CLANG_FLOAT_H #define __CLANG_FLOAT_H +#if defined(__MVS__) && __has_include_next() +#include_next +#else + /* If we're on MinGW, fall back to the system's float.h, which might have * additional definitions provided for Windows. * For more details see http://msdn.microsoft.com/en-us/library/y0ybw9fy.aspx @@ -165,4 +169,5 @@ # define FLT16_TRUE_MIN __FLT16_TRUE_MIN__ #endif /* __STDC_WANT_IEC_60559_TYPES_EXT__ */ +#endif /* __MVS__ */ #endif /* __CLANG_FLOAT_H */ diff --git a/clang/lib/Headers/inttypes.h b/clang/lib/Headers/inttypes.h index 1c894c4aca4975d7439ed3abda221818dbc57e94..5150d22f8b2e4ed1cae2d738c8a369541ec40cc5 100644 --- a/clang/lib/Headers/inttypes.h +++ b/clang/lib/Headers/inttypes.h @@ -13,6 +13,9 @@ #if !defined(_AIX) || !defined(_STD_TYPES_T) #define __CLANG_INTTYPES_H #endif +#if defined(__MVS__) && __has_include_next() +#include_next +#else #if defined(_MSC_VER) && _MSC_VER < 1800 #error MSVC does not have inttypes.h prior to Visual Studio 2013 @@ -94,4 +97,5 @@ #define SCNxFAST32 "x" #endif +#endif /* __MVS__ */ #endif /* __CLANG_INTTYPES_H */ diff --git a/clang/lib/Headers/iso646.h b/clang/lib/Headers/iso646.h index e0a20c6f1891b264c3ae7e116723bceea18919c1..b53fcd9b4e535932bb2cce3bf0f18a75a1dfa2ef 100644 --- a/clang/lib/Headers/iso646.h +++ b/clang/lib/Headers/iso646.h @@ -9,6 +9,9 @@ #ifndef __ISO646_H #define __ISO646_H +#if defined(__MVS__) && __has_include_next() +#include_next +#else #ifndef __cplusplus #define and && @@ -24,4 +27,5 @@ #define xor_eq ^= #endif +#endif /* __MVS__ */ #endif /* __ISO646_H */ diff --git a/clang/lib/Headers/limits.h b/clang/lib/Headers/limits.h index 15e6bbe0abcf7d765e928fecb14b34d5d76aaa1b..56dffe568486cc597243d11184321fcbb86230f1 100644 --- a/clang/lib/Headers/limits.h +++ b/clang/lib/Headers/limits.h @@ -9,6 +9,10 @@ #ifndef __CLANG_LIMITS_H #define __CLANG_LIMITS_H +#if defined(__MVS__) && __has_include_next() +#include_next +#else + /* The system's limits.h may, in turn, try to #include_next GCC's limits.h. Avert this #include_next madness. */ #if defined __GNUC__ && !defined _GCC_LIMITS_H_ @@ -122,4 +126,5 @@ #define ULONG_LONG_MAX (__LONG_LONG_MAX__*2ULL+1ULL) #endif +#endif /* __MVS__ */ #endif /* __CLANG_LIMITS_H */ diff --git a/clang/lib/Headers/stdalign.h b/clang/lib/Headers/stdalign.h index 158508e65d2b34c4fe725be55492bb1348e48661..56cdfa52d4bafaae5493523438553a218a35d133 100644 --- a/clang/lib/Headers/stdalign.h +++ b/clang/lib/Headers/stdalign.h @@ -10,6 +10,10 @@ #ifndef __STDALIGN_H #define __STDALIGN_H +#if defined(__MVS__) && __has_include_next() +#include_next +#else + #if defined(__cplusplus) || \ (defined(__STDC_VERSION__) && __STDC_VERSION__ < 202311L) #ifndef __cplusplus @@ -21,4 +25,5 @@ #define __alignof_is_defined 1 #endif /* __STDC_VERSION__ */ +#endif /* __MVS__ */ #endif /* __STDALIGN_H */ diff --git a/clang/lib/Headers/stdarg.h b/clang/lib/Headers/stdarg.h index 94b066566f084e34e7ff05b7c732b8e66eb83b00..6e7bd604b2df41b9bc417bd072cc6730c12bb72e 100644 --- a/clang/lib/Headers/stdarg.h +++ b/clang/lib/Headers/stdarg.h @@ -33,6 +33,16 @@ defined(__need_va_arg) || defined(__need___va_copy) || \ defined(__need_va_copy) +#if defined(__MVS__) && __has_include_next() +#define __STDARG_H +#undef __need___va_list +#undef __need_va_list +#undef __need_va_arg +#undef __need___va_copy +#undef __need_va_copy +#include_next + +#else #if !defined(__need___va_list) && !defined(__need_va_list) && \ !defined(__need_va_arg) && !defined(__need___va_copy) && \ !defined(__need_va_copy) @@ -76,4 +86,6 @@ #undef __need_va_copy #endif /* defined(__need_va_copy) */ +#endif /* __MVS__ */ + #endif diff --git a/clang/lib/Headers/stdbool.h b/clang/lib/Headers/stdbool.h index 9406aab0ca72c78dfee882cfb1b1dfbd496ed433..dfaad2b65a9b533f338dee48975e2062050487c6 100644 --- a/clang/lib/Headers/stdbool.h +++ b/clang/lib/Headers/stdbool.h @@ -12,6 +12,10 @@ #define __bool_true_false_are_defined 1 +#if defined(__MVS__) && __has_include_next() +#include_next +#else + #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201710L /* FIXME: We should be issuing a deprecation warning here, but cannot yet due * to system headers which include this header file unconditionally. @@ -31,4 +35,5 @@ #endif #endif +#endif /* __MVS__ */ #endif /* __STDBOOL_H */ diff --git a/clang/lib/Headers/stddef.h b/clang/lib/Headers/stddef.h index e0ad7b8d17aff93f0cfd937ac3d2a6decf0e4e5a..9ccc0a68fbff33bbf4f07ab38e949dc10e22f126 100644 --- a/clang/lib/Headers/stddef.h +++ b/clang/lib/Headers/stddef.h @@ -36,6 +36,22 @@ defined(__need_unreachable) || defined(__need_max_align_t) || \ defined(__need_offsetof) || defined(__need_wint_t) +#if defined(__MVS__) && __has_include_next() +#define __STDDEF_H +#undef __need_ptrdiff_t +#undef __need_size_t +#undef __need_rsize_t +#undef __need_wchar_t +#undef __need_NULL +#undef __need_nullptr_t +#undef __need_unreachable +#undef __need_max_align_t +#undef __need_offsetof +#undef __need_wint_t +#include_next + +#else + #if !defined(__need_ptrdiff_t) && !defined(__need_size_t) && \ !defined(__need_rsize_t) && !defined(__need_wchar_t) && \ !defined(__need_NULL) && !defined(__need_nullptr_t) && \ @@ -120,4 +136,5 @@ __WINT_TYPE__ directly; accommodate both by requiring __need_wint_t */ #undef __need_wint_t #endif /* __need_wint_t */ +#endif /* __MVS__ */ #endif diff --git a/clang/lib/Headers/stdint.h b/clang/lib/Headers/stdint.h index b6699b6ca3d4bb2faa69a9dbd2ee4560dd6018c4..01feab7b1ee2c206b22447dabaf9515086f90006 100644 --- a/clang/lib/Headers/stdint.h +++ b/clang/lib/Headers/stdint.h @@ -14,6 +14,10 @@ #define __CLANG_STDINT_H #endif +#if defined(__MVS__) && __has_include_next() +#include_next +#else + /* If we're hosted, fall back to the system's stdint.h, which might have * additional definitions. */ @@ -947,4 +951,5 @@ typedef __UINTMAX_TYPE__ uintmax_t; #endif #endif /* __STDC_HOSTED__ */ +#endif /* __MVS__ */ #endif /* __CLANG_STDINT_H */ diff --git a/clang/lib/Headers/stdnoreturn.h b/clang/lib/Headers/stdnoreturn.h index c90bf77e840e169c3977c0c8ba76eb704b82c802..6a9b209c7218bd116049585098401dd1bb4dc498 100644 --- a/clang/lib/Headers/stdnoreturn.h +++ b/clang/lib/Headers/stdnoreturn.h @@ -10,9 +10,15 @@ #ifndef __STDNORETURN_H #define __STDNORETURN_H +#if defined(__MVS__) && __has_include_next() +#include_next +#else + #define noreturn _Noreturn #define __noreturn_is_defined 1 +#endif /* __MVS__ */ + #if (defined(__STDC_VERSION__) && __STDC_VERSION__ > 201710L) && \ !defined(_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS) /* The noreturn macro is deprecated in C23. We do not mark it as such because diff --git a/clang/lib/Headers/varargs.h b/clang/lib/Headers/varargs.h index d241b7de3cb2a8590d7f7b4c3d935496d9b8fc44..d33ddc5ae7f8a541b1433c129bf0f7b3217ce20d 100644 --- a/clang/lib/Headers/varargs.h +++ b/clang/lib/Headers/varargs.h @@ -8,5 +8,9 @@ */ #ifndef __VARARGS_H #define __VARARGS_H - #error "Please use instead of " +#if defined(__MVS__) && __has_include_next() +#include_next +#else +#error "Please use instead of " +#endif /* __MVS__ */ #endif diff --git a/clang/lib/Headers/zos_wrappers/builtins.h b/clang/lib/Headers/zos_wrappers/builtins.h new file mode 100644 index 0000000000000000000000000000000000000000..1f0d0e27ecb3a486088c0c1513841391a5146cfb --- /dev/null +++ b/clang/lib/Headers/zos_wrappers/builtins.h @@ -0,0 +1,18 @@ +/*===---- builtins.h - z/Architecture Builtin Functions --------------------=== + * + * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. + * See https://llvm.org/LICENSE.txt for license information. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + * + *===-----------------------------------------------------------------------=== + */ + +#ifndef __ZOS_WRAPPERS_BUILTINS_H +#define __ZOS_WRAPPERS_BUILTINS_H +#if defined(__MVS__) +#include_next +#if defined(__VEC__) +#include +#endif +#endif /* defined(__MVS__) */ +#endif /* __ZOS_WRAPPERS_BUILTINS_H */ diff --git a/clang/lib/InstallAPI/FileList.cpp b/clang/lib/InstallAPI/FileList.cpp index 8a01248659b7d716dca426528071a5d95eeb07d9..65610903840af76e83be221f24f93a1bccb3e34c 100644 --- a/clang/lib/InstallAPI/FileList.cpp +++ b/clang/lib/InstallAPI/FileList.cpp @@ -51,6 +51,7 @@ private: public: std::unique_ptr InputBuffer; + clang::FileManager *FM; unsigned Version; HeaderSeq HeaderList; @@ -124,6 +125,12 @@ Error Implementation::parseHeaders(Array &Headers) { HeaderFile{PathStr, *Type, /*IncludeName=*/"", Language}); continue; } + + if (FM) + if (!FM->getOptionalFileRef(PathStr)) + return createFileError( + PathStr, make_error_code(std::errc::no_such_file_or_directory)); + auto IncludeName = createIncludeHeaderName(PathStr); HeaderList.emplace_back(PathStr, *Type, IncludeName.has_value() ? IncludeName.value() : "", @@ -170,9 +177,10 @@ Error Implementation::parse(StringRef Input) { llvm::Error FileListReader::loadHeaders(std::unique_ptr InputBuffer, - HeaderSeq &Destination) { + HeaderSeq &Destination, clang::FileManager *FM) { Implementation Impl; Impl.InputBuffer = std::move(InputBuffer); + Impl.FM = FM; if (llvm::Error Err = Impl.parse(Impl.InputBuffer->getBuffer())) return Err; diff --git a/clang/lib/Lex/Pragma.cpp b/clang/lib/Lex/Pragma.cpp index 499813f8ab7df0e6f81f8b84e2d8ea5b6cd5399b..10f0ab7180e62d09d41debe9e8fb7bb96982f280 100644 --- a/clang/lib/Lex/Pragma.cpp +++ b/clang/lib/Lex/Pragma.cpp @@ -1444,7 +1444,8 @@ struct PragmaWarningHandler : public PragmaHandler { .Case("once", PPCallbacks::PWS_Once) .Case("suppress", PPCallbacks::PWS_Suppress) .Default(-1); - if ((SpecifierValid = SpecifierInt != -1)) + SpecifierValid = SpecifierInt != -1; + if (SpecifierValid) Specifier = static_cast(SpecifierInt); diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp index 05ad5ecbfaa0cff6e311750f7499d848e9c17b6e..4e4b05b21383e1dcf2ab1ea82a5d099b3b1feb54 100644 --- a/clang/lib/Parse/ParseDecl.cpp +++ b/clang/lib/Parse/ParseDecl.cpp @@ -91,13 +91,23 @@ static StringRef normalizeAttrName(StringRef Name) { return Name; } -/// isAttributeLateParsed - Return true if the attribute has arguments that -/// require late parsing. -static bool isAttributeLateParsed(const IdentifierInfo &II) { +/// returns true iff attribute is annotated with `LateAttrParseExperimentalExt` +/// in `Attr.td`. +static bool IsAttributeLateParsedExperimentalExt(const IdentifierInfo &II) { +#define CLANG_ATTR_LATE_PARSED_EXPERIMENTAL_EXT_LIST + return llvm::StringSwitch(normalizeAttrName(II.getName())) +#include "clang/Parse/AttrParserStringSwitches.inc" + .Default(false); +#undef CLANG_ATTR_LATE_PARSED_EXPERIMENTAL_EXT_LIST +} + +/// returns true iff attribute is annotated with `LateAttrParseStandard` in +/// `Attr.td`. +static bool IsAttributeLateParsedStandard(const IdentifierInfo &II) { #define CLANG_ATTR_LATE_PARSED_LIST - return llvm::StringSwitch(normalizeAttrName(II.getName())) + return llvm::StringSwitch(normalizeAttrName(II.getName())) #include "clang/Parse/AttrParserStringSwitches.inc" - .Default(false); + .Default(false); #undef CLANG_ATTR_LATE_PARSED_LIST } @@ -222,8 +232,26 @@ void Parser::ParseGNUAttributes(ParsedAttributes &Attrs, continue; } + bool LateParse = false; + if (!LateAttrs) + LateParse = false; + else if (LateAttrs->lateAttrParseExperimentalExtOnly()) { + // The caller requested that this attribute **only** be late + // parsed for `LateAttrParseExperimentalExt` attributes. This will + // only be late parsed if the experimental language option is enabled. + LateParse = getLangOpts().ExperimentalLateParseAttributes && + IsAttributeLateParsedExperimentalExt(*AttrName); + } else { + // The caller did not restrict late parsing to only + // `LateAttrParseExperimentalExt` attributes so late parse + // both `LateAttrParseStandard` and `LateAttrParseExperimentalExt` + // attributes. + LateParse = IsAttributeLateParsedExperimentalExt(*AttrName) || + IsAttributeLateParsedStandard(*AttrName); + } + // Handle "parameterized" attributes - if (!LateAttrs || !isAttributeLateParsed(*AttrName)) { + if (!LateParse) { ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, &EndLoc, nullptr, SourceLocation(), ParsedAttr::Form::GNU(), D); continue; @@ -2998,7 +3026,7 @@ bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, << TokenName << TagName << getLangOpts().CPlusPlus << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName); - if (Actions.LookupParsedName(R, getCurScope(), SS)) { + if (Actions.LookupName(R, getCurScope())) { for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) @@ -7038,18 +7066,23 @@ void Parser::ParseDirectDeclarator(Declarator &D) { void Parser::ParseDecompositionDeclarator(Declarator &D) { assert(Tok.is(tok::l_square)); + TentativeParsingAction PA(*this); + BalancedDelimiterTracker T(*this, tok::l_square); + T.consumeOpen(); + + if (isCXX11AttributeSpecifier()) + DiagnoseAndSkipCXX11Attributes(); + // If this doesn't look like a structured binding, maybe it's a misplaced // array declarator. - // FIXME: Consume the l_square first so we don't need extra lookahead for - // this. - if (!(NextToken().is(tok::identifier) && - GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) && - !(NextToken().is(tok::r_square) && - GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace))) + if (!(Tok.is(tok::identifier) && + NextToken().isOneOf(tok::comma, tok::r_square, tok::kw_alignas, + tok::l_square)) && + !(Tok.is(tok::r_square) && + NextToken().isOneOf(tok::equal, tok::l_brace))) { + PA.Revert(); return ParseMisplacedBracketDeclarator(D); - - BalancedDelimiterTracker T(*this, tok::l_square); - T.consumeOpen(); + } SmallVector Bindings; while (Tok.isNot(tok::r_square)) { @@ -7074,13 +7107,27 @@ void Parser::ParseDecompositionDeclarator(Declarator &D) { } } + if (isCXX11AttributeSpecifier()) + DiagnoseAndSkipCXX11Attributes(); + if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected) << tok::identifier; break; } - Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()}); + IdentifierInfo *II = Tok.getIdentifierInfo(); + SourceLocation Loc = Tok.getLocation(); ConsumeToken(); + + ParsedAttributes Attrs(AttrFactory); + if (isCXX11AttributeSpecifier()) { + Diag(Tok, getLangOpts().CPlusPlus26 + ? diag::warn_cxx23_compat_decl_attrs_on_binding + : diag::ext_decl_attrs_on_binding); + MaybeParseCXX11Attributes(Attrs); + } + + Bindings.push_back({II, Loc, std::move(Attrs)}); } if (Tok.isNot(tok::r_square)) @@ -7095,6 +7142,8 @@ void Parser::ParseDecompositionDeclarator(Declarator &D) { T.consumeClose(); } + PA.Commit(); + return D.setDecompositionBindings(T.getOpenLocation(), Bindings, T.getCloseLocation()); } @@ -7367,12 +7416,20 @@ void Parser::ParseFunctionDeclarator(Declarator &D, std::optional ThisScope; InitCXXThisScopeForDeclaratorIfRelevant(D, DS, ThisScope); - // Parse exception-specification[opt]. - // FIXME: Per [class.mem]p6, all exception-specifications at class scope - // should be delayed, including those for non-members (eg, friend - // declarations). But only applying this to member declarations is - // consistent with what other implementations do. - bool Delayed = D.isFirstDeclarationOfMember() && + // C++ [class.mem.general]p8: + // A complete-class context of a class (template) is a + // - function body, + // - default argument, + // - default template argument, + // - noexcept-specifier, or + // - default member initializer + // within the member-specification of the class or class template. + // + // Parse exception-specification[opt]. If we are in the + // member-specification of a class or class template, this is a + // complete-class context and parsing of the noexcept-specifier should be + // delayed (even if this is a friend declaration). + bool Delayed = D.getContext() == DeclaratorContext::Member && D.isFunctionDeclaratorAFunctionDeclaration(); if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) && GetLookAheadToken(0).is(tok::kw_noexcept) && diff --git a/clang/lib/Parse/ParseOpenACC.cpp b/clang/lib/Parse/ParseOpenACC.cpp index 29326f5d993a9d56b861a61bfbaa437518b62295..2d1ec6539b2fd1c5a990c5f4391348382dac3f26 100644 --- a/clang/lib/Parse/ParseOpenACC.cpp +++ b/clang/lib/Parse/ParseOpenACC.cpp @@ -86,6 +86,10 @@ OpenACCClauseKind getOpenACCClauseKind(Token Tok) { if (Tok.is(tok::kw_if)) return OpenACCClauseKind::If; + // 'private' is also a keyword, make sure we pare it correctly. + if (Tok.is(tok::kw_private)) + return OpenACCClauseKind::Private; + if (!Tok.is(tok::identifier)) return OpenACCClauseKind::Invalid; @@ -682,28 +686,6 @@ bool Parser::ParseOpenACCIntExprList(OpenACCDirectiveKind DK, return false; } -bool Parser::ParseOpenACCClauseVarList(OpenACCClauseKind Kind) { - // FIXME: Future clauses will require 'special word' parsing, check for one, - // then parse it based on whether it is a clause that requires a 'special - // word'. - (void)Kind; - - // If the var parsing fails, skip until the end of the directive as this is - // an expression and gets messy if we try to continue otherwise. - if (ParseOpenACCVar()) - return true; - - while (!getCurToken().isOneOf(tok::r_paren, tok::annot_pragma_openacc_end)) { - ExpectAndConsume(tok::comma); - - // If the var parsing fails, skip until the end of the directive as this is - // an expression and gets messy if we try to continue otherwise. - if (ParseOpenACCVar()) - return true; - } - return false; -} - /// OpenACC 3.3 Section 2.4: /// The argument to the device_type clause is a comma-separated list of one or /// more device architecture name identifiers, or an asterisk. @@ -917,28 +899,19 @@ Parser::OpenACCClauseParseResult Parser::ParseOpenACCClauseParams( case OpenACCClauseKind::CopyIn: tryParseAndConsumeSpecialTokenKind( *this, OpenACCSpecialTokenKind::ReadOnly, ClauseKind); - if (ParseOpenACCClauseVarList(ClauseKind)) { - Parens.skipToEnd(); - return OpenACCCanContinue(); - } + ParseOpenACCVarList(); break; case OpenACCClauseKind::Create: case OpenACCClauseKind::CopyOut: tryParseAndConsumeSpecialTokenKind(*this, OpenACCSpecialTokenKind::Zero, ClauseKind); - if (ParseOpenACCClauseVarList(ClauseKind)) { - Parens.skipToEnd(); - return OpenACCCanContinue(); - } + ParseOpenACCVarList(); break; case OpenACCClauseKind::Reduction: // If we're missing a clause-kind (or it is invalid), see if we can parse // the var-list anyway. ParseReductionOperator(*this); - if (ParseOpenACCClauseVarList(ClauseKind)) { - Parens.skipToEnd(); - return OpenACCCanContinue(); - } + ParseOpenACCVarList(); break; case OpenACCClauseKind::Self: // The 'self' clause is a var-list instead of a 'condition' in the case of @@ -958,12 +931,11 @@ Parser::OpenACCClauseParseResult Parser::ParseOpenACCClauseParams( case OpenACCClauseKind::Link: case OpenACCClauseKind::NoCreate: case OpenACCClauseKind::Present: - case OpenACCClauseKind::Private: case OpenACCClauseKind::UseDevice: - if (ParseOpenACCClauseVarList(ClauseKind)) { - Parens.skipToEnd(); - return OpenACCCanContinue(); - } + ParseOpenACCVarList(); + break; + case OpenACCClauseKind::Private: + ParsedClause.setVarListDetails(ParseOpenACCVarList()); break; case OpenACCClauseKind::Collapse: { tryParseAndConsumeSpecialTokenKind(*this, OpenACCSpecialTokenKind::Force, @@ -1227,16 +1199,51 @@ ExprResult Parser::ParseOpenACCBindClauseArgument() { /// OpenACC 3.3, section 1.6: /// In this spec, a 'var' (in italics) is one of the following: -/// - a variable name (a scalar, array, or compisite variable name) +/// - a variable name (a scalar, array, or composite variable name) /// - a subarray specification with subscript ranges /// - an array element /// - a member of a composite variable /// - a common block name between slashes (fortran only) -bool Parser::ParseOpenACCVar() { +Parser::OpenACCVarParseResult Parser::ParseOpenACCVar() { OpenACCArraySectionRAII ArraySections(*this); - ExprResult Res = - getActions().CorrectDelayedTyposInExpr(ParseAssignmentExpression()); - return Res.isInvalid(); + + ExprResult Res = ParseAssignmentExpression(); + if (!Res.isUsable()) + return {Res, OpenACCParseCanContinue::Cannot}; + + Res = getActions().CorrectDelayedTyposInExpr(Res.get()); + if (!Res.isUsable()) + return {Res, OpenACCParseCanContinue::Can}; + + Res = getActions().OpenACC().ActOnVar(Res.get()); + + return {Res, OpenACCParseCanContinue::Can}; +} + +llvm::SmallVector Parser::ParseOpenACCVarList() { + llvm::SmallVector Vars; + + auto [Res, CanContinue] = ParseOpenACCVar(); + if (Res.isUsable()) { + Vars.push_back(Res.get()); + } else if (CanContinue == OpenACCParseCanContinue::Cannot) { + SkipUntil(tok::r_paren, tok::annot_pragma_openacc_end, StopBeforeMatch); + return Vars; + } + + while (!getCurToken().isOneOf(tok::r_paren, tok::annot_pragma_openacc_end)) { + ExpectAndConsume(tok::comma); + + auto [Res, CanContinue] = ParseOpenACCVar(); + + if (Res.isUsable()) { + Vars.push_back(Res.get()); + } else if (CanContinue == OpenACCParseCanContinue::Cannot) { + SkipUntil(tok::r_paren, tok::annot_pragma_openacc_end, StopBeforeMatch); + return Vars; + } + } + return Vars; } /// OpenACC 3.3, section 2.10: @@ -1259,24 +1266,9 @@ void Parser::ParseOpenACCCacheVarList() { // Sema/AST generation. } - bool FirstArray = true; - while (!getCurToken().isOneOf(tok::r_paren, tok::annot_pragma_openacc_end)) { - if (!FirstArray) - ExpectAndConsume(tok::comma); - FirstArray = false; - - // OpenACC 3.3, section 2.10: - // A 'var' in a cache directive must be a single array element or a simple - // subarray. In C and C++, a simple subarray is an array name followed by - // an extended array range specification in brackets, with a start and - // length such as: - // - // arr[lower:length] - // - if (ParseOpenACCVar()) - SkipUntil(tok::r_paren, tok::annot_pragma_openacc_end, tok::comma, - StopBeforeMatch); - } + // ParseOpenACCVarList should leave us before a r-paren, so no need to skip + // anything here. + ParseOpenACCVarList(); } Parser::OpenACCDirectiveParseInfo Parser::ParseOpenACCDirective() { diff --git a/clang/lib/Parse/ParseOpenMP.cpp b/clang/lib/Parse/ParseOpenMP.cpp index 480201bc06f61392b5aaf9160f03996e3b91d9df..53d89ce2fa3e99f5f0e1779a917a88d918ce7b96 100644 --- a/clang/lib/Parse/ParseOpenMP.cpp +++ b/clang/lib/Parse/ParseOpenMP.cpp @@ -4228,13 +4228,20 @@ bool Parser::parseMapperModifier(SemaOpenMP::OpenMPVarListDataTy &Data) { return T.consumeClose(); } +static OpenMPMapClauseKind isMapType(Parser &P); + /// Parse map-type-modifiers in map clause. -/// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list) +/// map([ [map-type-modifier[,] [map-type-modifier[,] ...] [map-type] : ] list) /// where, map-type-modifier ::= always | close | mapper(mapper-identifier) | /// present +/// where, map-type ::= alloc | delete | from | release | to | tofrom bool Parser::parseMapTypeModifiers(SemaOpenMP::OpenMPVarListDataTy &Data) { + bool HasMapType = false; + SourceLocation PreMapLoc = Tok.getLocation(); + StringRef PreMapName = ""; while (getCurToken().isNot(tok::colon)) { OpenMPMapModifierKind TypeModifier = isMapModifier(*this); + OpenMPMapClauseKind MapKind = isMapType(*this); if (TypeModifier == OMPC_MAP_MODIFIER_always || TypeModifier == OMPC_MAP_MODIFIER_close || TypeModifier == OMPC_MAP_MODIFIER_present || @@ -4257,6 +4264,19 @@ bool Parser::parseMapTypeModifiers(SemaOpenMP::OpenMPVarListDataTy &Data) { Diag(Data.MapTypeModifiersLoc.back(), diag::err_omp_missing_comma) << "map type modifier"; + } else if (getLangOpts().OpenMP >= 60 && MapKind != OMPC_MAP_unknown) { + if (!HasMapType) { + HasMapType = true; + Data.ExtraModifier = MapKind; + MapKind = OMPC_MAP_unknown; + PreMapLoc = Tok.getLocation(); + PreMapName = Tok.getIdentifierInfo()->getName(); + } else { + Diag(Tok, diag::err_omp_more_one_map_type); + Diag(PreMapLoc, diag::note_previous_map_type_specified_here) + << PreMapName; + } + ConsumeToken(); } else { // For the case of unknown map-type-modifier or a map-type. // Map-type is followed by a colon; the function returns when it @@ -4267,8 +4287,14 @@ bool Parser::parseMapTypeModifiers(SemaOpenMP::OpenMPVarListDataTy &Data) { continue; } // Potential map-type token as it is followed by a colon. - if (PP.LookAhead(0).is(tok::colon)) - return false; + if (PP.LookAhead(0).is(tok::colon)) { + if (getLangOpts().OpenMP >= 60) { + break; + } else { + return false; + } + } + Diag(Tok, diag::err_omp_unknown_map_type_modifier) << (getLangOpts().OpenMP >= 51 ? (getLangOpts().OpenMP >= 52 ? 2 : 1) : 0) @@ -4278,6 +4304,14 @@ bool Parser::parseMapTypeModifiers(SemaOpenMP::OpenMPVarListDataTy &Data) { if (getCurToken().is(tok::comma)) ConsumeToken(); } + if (getLangOpts().OpenMP >= 60 && !HasMapType) { + if (!Tok.is(tok::colon)) { + Diag(Tok, diag::err_omp_unknown_map_type); + ConsumeToken(); + } else { + Data.ExtraModifier = OMPC_MAP_unknown; + } + } return false; } @@ -4675,8 +4709,10 @@ bool Parser::ParseOpenMPVarList(OpenMPDirectiveKind DKind, // Only parse map-type-modifier[s] and map-type if a colon is present in // the map clause. if (ColonPresent) { + if (getLangOpts().OpenMP >= 60 && getCurToken().is(tok::colon)) + Diag(Tok, diag::err_omp_map_modifier_specification_list); IsInvalidMapperModifier = parseMapTypeModifiers(Data); - if (!IsInvalidMapperModifier) + if (getLangOpts().OpenMP < 60 && !IsInvalidMapperModifier) parseMapType(*this, Data); else SkipUntil(tok::colon, tok::annot_pragma_openmp_end, StopBeforeMatch); diff --git a/clang/lib/Sema/DeclSpec.cpp b/clang/lib/Sema/DeclSpec.cpp index b79683bb32a69ec559c401fb3329c648cfdea686..60e81890257002a52993d367b876ab305e520d45 100644 --- a/clang/lib/Sema/DeclSpec.cpp +++ b/clang/lib/Sema/DeclSpec.cpp @@ -293,7 +293,7 @@ DeclaratorChunk DeclaratorChunk::getFunction(bool hasProto, void Declarator::setDecompositionBindings( SourceLocation LSquareLoc, - ArrayRef Bindings, + MutableArrayRef Bindings, SourceLocation RSquareLoc) { assert(!hasName() && "declarator given multiple names!"); @@ -317,7 +317,7 @@ void Declarator::setDecompositionBindings( new DecompositionDeclarator::Binding[Bindings.size()]; BindingGroup.DeleteBindings = true; } - std::uninitialized_copy(Bindings.begin(), Bindings.end(), + std::uninitialized_move(Bindings.begin(), Bindings.end(), BindingGroup.Bindings); } } @@ -1202,7 +1202,10 @@ void DeclSpec::Finish(Sema &S, const PrintingPolicy &Policy) { !S.Context.getTargetInfo().hasFeature("power8-vector")) S.Diag(TSTLoc, diag::err_invalid_vector_int128_decl_spec); - if (TypeAltiVecBool) { + // Complex vector types are not supported. + if (TypeSpecComplex != TSC_unspecified) + S.Diag(TSCLoc, diag::err_invalid_vector_complex_decl_spec); + else if (TypeAltiVecBool) { // Sign specifiers are not allowed with vector bool. (PIM 2.1) if (getTypeSpecSign() != TypeSpecifierSign::Unspecified) { S.Diag(TSSLoc, diag::err_invalid_vector_bool_decl_spec) diff --git a/clang/lib/Sema/HLSLExternalSemaSource.cpp b/clang/lib/Sema/HLSLExternalSemaSource.cpp index 1a1febf7a3524118d9179d14575e3c870a5a20c3..bb283c54b3d29c13f2de137a5e42d3fe3e282a63 100644 --- a/clang/lib/Sema/HLSLExternalSemaSource.cpp +++ b/clang/lib/Sema/HLSLExternalSemaSource.cpp @@ -126,12 +126,15 @@ struct BuiltinTypeDeclBuilder { static DeclRefExpr *lookupBuiltinFunction(ASTContext &AST, Sema &S, StringRef Name) { - CXXScopeSpec SS; IdentifierInfo &II = AST.Idents.get(Name, tok::TokenKind::identifier); DeclarationNameInfo NameInfo = DeclarationNameInfo(DeclarationName(&II), SourceLocation()); LookupResult R(S, NameInfo, Sema::LookupOrdinaryName); - S.LookupParsedName(R, S.getCurScope(), &SS, false); + // AllowBuiltinCreation is false but LookupDirect will create + // the builtin when searching the global scope anyways... + S.LookupName(R, S.getCurScope()); + // FIXME: If the builtin function was user-declared in global scope, + // this assert *will* fail. Should this call LookupBuiltin instead? assert(R.isSingleResult() && "Since this is a builtin it should always resolve!"); auto *VD = cast(R.getFoundDecl()); diff --git a/clang/lib/Sema/SemaAttr.cpp b/clang/lib/Sema/SemaAttr.cpp index a5dd158808f26b4bed173943d9940f7f76602d10..a83b1e8afadbc65f5980309d52270d14c9e08652 100644 --- a/clang/lib/Sema/SemaAttr.cpp +++ b/clang/lib/Sema/SemaAttr.cpp @@ -837,7 +837,7 @@ void Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope, IdentifierInfo *Name = IdTok.getIdentifierInfo(); LookupResult Lookup(*this, Name, IdTok.getLocation(), LookupOrdinaryName); - LookupParsedName(Lookup, curScope, nullptr, true); + LookupName(Lookup, curScope, /*AllowBuiltinCreation=*/true); if (Lookup.empty()) { Diag(PragmaLoc, diag::warn_pragma_unused_undeclared_var) diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp index e33113ab9c4c1d1e8080f5639a3798279cfc8e33..cf8840c63024d4c449649e3a64c57e6d56d21f2a 100644 --- a/clang/lib/Sema/SemaChecking.cpp +++ b/clang/lib/Sema/SemaChecking.cpp @@ -3164,13 +3164,20 @@ Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, const Expr *Arg = TheCall->getArg(0); const auto *TyA = Arg->getType()->getAs(); - if (!TyA) { + + QualType ElTy; + if (TyA) + ElTy = TyA->getElementType(); + else if (Arg->getType()->isSizelessVectorType()) + ElTy = Arg->getType()->getSizelessVectorEltType(Context); + + if (ElTy.isNull()) { Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type) << 1 << /* vector ty*/ 4 << Arg->getType(); return ExprError(); } - TheCall->setType(TyA->getElementType()); + TheCall->setType(ElTy); break; } @@ -3186,12 +3193,20 @@ Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, const Expr *Arg = TheCall->getArg(0); const auto *TyA = Arg->getType()->getAs(); - if (!TyA || !TyA->getElementType()->isIntegerType()) { + + QualType ElTy; + if (TyA) + ElTy = TyA->getElementType(); + else if (Arg->getType()->isSizelessVectorType()) + ElTy = Arg->getType()->getSizelessVectorEltType(Context); + + if (ElTy.isNull() || !ElTy->isIntegerType()) { Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type) << 1 << /* vector of integers */ 6 << Arg->getType(); return ExprError(); } - TheCall->setType(TyA->getElementType()); + + TheCall->setType(ElTy); break; } @@ -12544,6 +12559,17 @@ CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, return true; } + // Diagnose attempts to use '%P' with ObjC object types, which will result in + // dumping raw class data (like is-a pointer), not actual data. + if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::PArg && + ExprTy->isObjCObjectPointerType()) { + const CharSourceRange &CSR = + getSpecifierRange(StartSpecifier, SpecifierLen); + EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer), + E->getExprLoc(), false, CSR); + return true; + } + ArgType::MatchKind ImplicitMatch = ArgType::NoMatch; ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); ArgType::MatchKind OrigMatch = Match; diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp index e0745fe9a4536794f437579f5037d1169fef24bb..79fb6c0417e33d99610b2e45b195fe186a7346f2 100644 --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -832,7 +832,7 @@ static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, IdentifierInfo *&Name, SourceLocation NameLoc) { LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); - SemaRef.LookupParsedName(R, S, &SS); + SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType()); if (TagDecl *Tag = R.getAsSingle()) { StringRef FixItTagName; switch (Tag->getTagKind()) { @@ -869,7 +869,7 @@ static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, // Replace lookup results with just the tag decl. Result.clear(Sema::LookupTagName); - SemaRef.LookupParsedName(Result, S, &SS); + SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType()); return true; } @@ -896,7 +896,8 @@ Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, } LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); - LookupParsedName(Result, S, &SS, !CurMethod); + LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(), + /*AllowBuiltinCreation=*/!CurMethod); if (SS.isInvalid()) return NameClassification::Error(); @@ -1974,7 +1975,7 @@ static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts, // it is, by the bindings' expressions). bool IsAllPlaceholders = true; for (const auto *BD : DD->bindings()) { - if (BD->isReferenced()) + if (BD->isReferenced() || BD->hasAttr()) return false; IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts); } diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp index abdbc9d8830c03f6c70121e73f9f2427450cc577..157d42c09cfcd82ee572e0e8e6e594f6fa0721b7 100644 --- a/clang/lib/Sema/SemaDeclCXX.cpp +++ b/clang/lib/Sema/SemaDeclCXX.cpp @@ -910,6 +910,8 @@ Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, VarName); + ProcessDeclAttributeList(S, BD, *B.Attrs); + // Find the shadowed declaration before filtering for scope. NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() ? getShadowedDeclaration(BD, Previous) @@ -4517,7 +4519,7 @@ Sema::BuildMemInitializer(Decl *ConstructorD, DS.getBeginLoc(), DS.getEllipsisLoc()); } else { LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); - LookupParsedName(R, S, &SS); + LookupParsedName(R, S, &SS, /*ObjectType=*/QualType()); TypeDecl *TyD = R.getAsSingle(); if (!TyD) { @@ -12052,11 +12054,17 @@ bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { Template = Specialization->getSpecializedTemplate(); Arguments = Specialization->getTemplateArgs().data(); - } else if (const TemplateSpecializationType *TST = - Ty->getAs()) { - Template = dyn_cast_or_null( - TST->getTemplateName().getAsTemplateDecl()); - Arguments = TST->template_arguments().begin(); + } else { + const TemplateSpecializationType *TST = nullptr; + if (auto *ICN = Ty->getAs()) + TST = ICN->getInjectedTST(); + else + TST = Ty->getAs(); + if (TST) { + Template = dyn_cast_or_null( + TST->getTemplateName().getAsTemplateDecl()); + Arguments = TST->template_arguments().begin(); + } } if (!Template) return false; @@ -12262,7 +12270,7 @@ Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, // Lookup namespace name. LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); - LookupParsedName(R, S, &SS); + LookupParsedName(R, S, &SS, /*ObjectType=*/QualType()); if (R.isAmbiguous()) return nullptr; @@ -13721,7 +13729,7 @@ Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, // Lookup the namespace name. LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); - LookupParsedName(R, S, &SS); + LookupParsedName(R, S, &SS, /*ObjectType=*/QualType()); if (R.isAmbiguous()) return nullptr; @@ -19164,40 +19172,40 @@ void Sema::checkExceptionSpecification( } } -void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, - ExceptionSpecificationType EST, - SourceRange SpecificationRange, - ArrayRef DynamicExceptions, - ArrayRef DynamicExceptionRanges, - Expr *NoexceptExpr) { - if (!MethodD) +void Sema::actOnDelayedExceptionSpecification( + Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange, + ArrayRef DynamicExceptions, + ArrayRef DynamicExceptionRanges, Expr *NoexceptExpr) { + if (!D) return; - // Dig out the method we're referring to. - if (FunctionTemplateDecl *FunTmpl = dyn_cast(MethodD)) - MethodD = FunTmpl->getTemplatedDecl(); + // Dig out the function we're referring to. + if (FunctionTemplateDecl *FTD = dyn_cast(D)) + D = FTD->getTemplatedDecl(); - CXXMethodDecl *Method = dyn_cast(MethodD); - if (!Method) + FunctionDecl *FD = dyn_cast(D); + if (!FD) return; // Check the exception specification. llvm::SmallVector Exceptions; FunctionProtoType::ExceptionSpecInfo ESI; - checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, + checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions, DynamicExceptionRanges, NoexceptExpr, Exceptions, ESI); // Update the exception specification on the function type. - Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); + Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true); - if (Method->isStatic()) - checkThisInStaticMemberFunctionExceptionSpec(Method); + if (CXXMethodDecl *MD = dyn_cast(D)) { + if (MD->isStatic()) + checkThisInStaticMemberFunctionExceptionSpec(MD); - if (Method->isVirtual()) { - // Check overrides, which we previously had to delay. - for (const CXXMethodDecl *O : Method->overridden_methods()) - CheckOverridingFunctionExceptionSpec(Method, O); + if (MD->isVirtual()) { + // Check overrides, which we previously had to delay. + for (const CXXMethodDecl *O : MD->overridden_methods()) + CheckOverridingFunctionExceptionSpec(MD, O); + } } } diff --git a/clang/lib/Sema/SemaExceptionSpec.cpp b/clang/lib/Sema/SemaExceptionSpec.cpp index c9dd6bb2413e38b204ed473ee9a9f88e610d5484..41bf273d12f2f32441253cb75eddb92419281deb 100644 --- a/clang/lib/Sema/SemaExceptionSpec.cpp +++ b/clang/lib/Sema/SemaExceptionSpec.cpp @@ -258,13 +258,14 @@ Sema::UpdateExceptionSpec(FunctionDecl *FD, } static bool exceptionSpecNotKnownYet(const FunctionDecl *FD) { - auto *MD = dyn_cast(FD); - if (!MD) + ExceptionSpecificationType EST = + FD->getType()->castAs()->getExceptionSpecType(); + if (EST == EST_Unparsed) + return true; + else if (EST != EST_Unevaluated) return false; - - auto EST = MD->getType()->castAs()->getExceptionSpecType(); - return EST == EST_Unparsed || - (EST == EST_Unevaluated && MD->getParent()->isBeingDefined()); + const DeclContext *DC = FD->getLexicalDeclContext(); + return DC->isRecord() && cast(DC)->isBeingDefined(); } static bool CheckEquivalentExceptionSpecImpl( diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 50f92c496a539a7c1ec459d54831cd6ecbe7f014..0c37f43f75401bd59d7e9e96da4e1da01871dee3 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -673,8 +673,9 @@ ExprResult Sema::DefaultLvalueConversion(Expr *E) { // expressions of certain types in C++. if (getLangOpts().CPlusPlus && (E->getType() == Context.OverloadTy || - T->isDependentType() || - T->isRecordType())) + // FIXME: This is a hack! We want the lvalue-to-rvalue conversion applied + // to pointer types even if the pointee type is dependent. + (T->isDependentType() && !T->isPointerType()) || T->isRecordType())) return E; // The C standard is actually really unclear on this point, and @@ -2751,8 +2752,8 @@ Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, if (isBoundsAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) { // See if this is reference to a field of struct. LookupResult R(*this, NameInfo, LookupMemberName); - // LookupParsedName handles a name lookup from within anonymous struct. - if (LookupParsedName(R, S, &SS)) { + // LookupName handles a name lookup from within anonymous struct. + if (LookupName(R, S)) { if (auto *VD = dyn_cast(R.getFoundDecl())) { QualType type = VD->getType().getNonReferenceType(); // This will eventually be translated into MemberExpr upon @@ -2773,20 +2774,19 @@ Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, // lookup to determine that it was a template name in the first place. If // this becomes a performance hit, we can work harder to preserve those // results until we get here but it's likely not worth it. - bool MemberOfUnknownSpecialization; AssumedTemplateKind AssumedTemplate; - if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, - MemberOfUnknownSpecialization, TemplateKWLoc, + if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(), + /*EnteringContext=*/false, TemplateKWLoc, &AssumedTemplate)) return ExprError(); - if (MemberOfUnknownSpecialization || - (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) + if (R.wasNotFoundInCurrentInstantiation()) return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, IsAddressOfOperand, TemplateArgs); } else { bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); - LookupParsedName(R, S, &SS, !IvarLookupFollowUp); + LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(), + /*AllowBuiltinCreation=*/!IvarLookupFollowUp); // If the result might be in a dependent base class, this is a dependent // id-expression. diff --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp index 779a41620033dc6a6cef9d3f7b694a654f6a061a..c1cb03e4ec7ae2088a983141c47202d4732a5089 100644 --- a/clang/lib/Sema/SemaExprCXX.cpp +++ b/clang/lib/Sema/SemaExprCXX.cpp @@ -9157,7 +9157,7 @@ Sema::CheckMicrosoftIfExistsSymbol(Scope *S, // Do the redeclaration lookup in the current scope. LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName, RedeclarationKind::NotForRedeclaration); - LookupParsedName(R, S, &SS); + LookupParsedName(R, S, &SS, /*ObjectType=*/QualType()); R.suppressDiagnostics(); switch (R.getResultKind()) { diff --git a/clang/lib/Sema/SemaExprMember.cpp b/clang/lib/Sema/SemaExprMember.cpp index 6e30716b9ae436b3eacec19f76a974734d116a9a..5facb14a18b7c2ae8031b68c769363d9f69a76cd 100644 --- a/clang/lib/Sema/SemaExprMember.cpp +++ b/clang/lib/Sema/SemaExprMember.cpp @@ -667,8 +667,8 @@ namespace { // classes, one of its base classes. class RecordMemberExprValidatorCCC final : public CorrectionCandidateCallback { public: - explicit RecordMemberExprValidatorCCC(const RecordType *RTy) - : Record(RTy->getDecl()) { + explicit RecordMemberExprValidatorCCC(QualType RTy) + : Record(RTy->getAsRecordDecl()) { // Don't add bare keywords to the consumer since they will always fail // validation by virtue of not being associated with any decls. WantTypeSpecifiers = false; @@ -713,58 +713,36 @@ private: } static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R, - Expr *BaseExpr, - const RecordType *RTy, + Expr *BaseExpr, QualType RTy, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, bool HasTemplateArgs, SourceLocation TemplateKWLoc, TypoExpr *&TE) { SourceRange BaseRange = BaseExpr ? BaseExpr->getSourceRange() : SourceRange(); - RecordDecl *RDecl = RTy->getDecl(); - if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) && - SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0), - diag::err_typecheck_incomplete_tag, - BaseRange)) + if (!RTy->isDependentType() && + !SemaRef.isThisOutsideMemberFunctionBody(RTy) && + SemaRef.RequireCompleteType( + OpLoc, RTy, diag::err_typecheck_incomplete_tag, BaseRange)) return true; - if (HasTemplateArgs || TemplateKWLoc.isValid()) { - // LookupTemplateName doesn't expect these both to exist simultaneously. - QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0); + // LookupTemplateName/LookupParsedName don't expect these both to exist + // simultaneously. + QualType ObjectType = SS.isSet() ? QualType() : RTy; + if (HasTemplateArgs || TemplateKWLoc.isValid()) + return SemaRef.LookupTemplateName(R, + /*S=*/nullptr, SS, ObjectType, + /*EnteringContext=*/false, TemplateKWLoc); - bool MOUS; - return SemaRef.LookupTemplateName(R, nullptr, SS, ObjectType, false, MOUS, - TemplateKWLoc); - } - - DeclContext *DC = RDecl; - if (SS.isSet()) { - // If the member name was a qualified-id, look into the - // nested-name-specifier. - DC = SemaRef.computeDeclContext(SS, false); - - if (SemaRef.RequireCompleteDeclContext(SS, DC)) { - SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag) - << SS.getRange() << DC; - return true; - } - - assert(DC && "Cannot handle non-computable dependent contexts in lookup"); - - if (!isa(DC)) { - SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass) - << DC << SS.getRange(); - return true; - } - } - - // The record definition is complete, now look up the member. - SemaRef.LookupQualifiedName(R, DC, SS); + SemaRef.LookupParsedName(R, /*S=*/nullptr, &SS, ObjectType); - if (!R.empty()) + if (!R.empty() || R.wasNotFoundInCurrentInstantiation()) return false; DeclarationName Typo = R.getLookupName(); SourceLocation TypoLoc = R.getNameLoc(); + // Recompute the lookup context. + DeclContext *DC = SS.isSet() ? SemaRef.computeDeclContext(SS) + : SemaRef.computeDeclContext(RTy); struct QueryState { Sema &SemaRef; @@ -788,7 +766,8 @@ static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R, << Typo << DC << DroppedSpecifier << SS.getRange()); } else { - SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << DC << BaseRange; + SemaRef.Diag(TypoLoc, diag::err_no_member) + << Typo << DC << (SS.isSet() ? SS.getRange() : BaseRange); } }, [=](Sema &SemaRef, TypoExpr *TE, TypoCorrection TC) mutable { @@ -814,34 +793,25 @@ static ExprResult LookupMemberExpr(Sema &S, LookupResult &R, Decl *ObjCImpDecl, bool HasTemplateArgs, SourceLocation TemplateKWLoc); -ExprResult -Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType, - SourceLocation OpLoc, bool IsArrow, - CXXScopeSpec &SS, - SourceLocation TemplateKWLoc, - NamedDecl *FirstQualifierInScope, - const DeclarationNameInfo &NameInfo, - const TemplateArgumentListInfo *TemplateArgs, - const Scope *S, - ActOnMemberAccessExtraArgs *ExtraArgs) { - if (BaseType->isDependentType() || - (SS.isSet() && isDependentScopeSpecifier(SS)) || - NameInfo.getName().isDependentName()) - return ActOnDependentMemberExpr(Base, BaseType, - IsArrow, OpLoc, - SS, TemplateKWLoc, FirstQualifierInScope, - NameInfo, TemplateArgs); - +ExprResult Sema::BuildMemberReferenceExpr( + Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, + CXXScopeSpec &SS, SourceLocation TemplateKWLoc, + NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, + const TemplateArgumentListInfo *TemplateArgs, const Scope *S, + ActOnMemberAccessExtraArgs *ExtraArgs) { LookupResult R(*this, NameInfo, LookupMemberName); + if (SS.isInvalid()) + return ExprError(); + // Implicit member accesses. if (!Base) { TypoExpr *TE = nullptr; QualType RecordTy = BaseType; if (IsArrow) RecordTy = RecordTy->castAs()->getPointeeType(); - if (LookupMemberExprInRecord( - *this, R, nullptr, RecordTy->castAs(), OpLoc, IsArrow, - SS, TemplateArgs != nullptr, TemplateKWLoc, TE)) + if (LookupMemberExprInRecord(*this, R, nullptr, RecordTy, OpLoc, IsArrow, + SS, TemplateArgs != nullptr, TemplateKWLoc, + TE)) return ExprError(); if (TE) return TE; @@ -968,19 +938,6 @@ BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow, NameInfo.getLoc()); } -MemberExpr *Sema::BuildMemberExpr( - Expr *Base, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec *SS, - SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, - bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, - QualType Ty, ExprValueKind VK, ExprObjectKind OK, - const TemplateArgumentListInfo *TemplateArgs) { - NestedNameSpecifierLoc NNS = - SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); - return BuildMemberExpr(Base, IsArrow, OpLoc, NNS, TemplateKWLoc, Member, - FoundDecl, HadMultipleCandidates, MemberNameInfo, Ty, - VK, OK, TemplateArgs); -} - MemberExpr *Sema::BuildMemberExpr( Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, @@ -1033,6 +990,17 @@ Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType, const Scope *S, bool SuppressQualifierCheck, ActOnMemberAccessExtraArgs *ExtraArgs) { + assert(!SS.isInvalid() && "nested-name-specifier cannot be invalid"); + // If the member wasn't found in the current instantiation, or if the + // arrow operator was used with a dependent non-pointer object expression, + // build a CXXDependentScopeMemberExpr. + if (R.wasNotFoundInCurrentInstantiation() || + (IsArrow && !BaseExprType->isPointerType() && + BaseExprType->isDependentType())) + return ActOnDependentMemberExpr(BaseExpr, BaseExprType, IsArrow, OpLoc, SS, + TemplateKWLoc, FirstQualifierInScope, + R.getLookupNameInfo(), TemplateArgs); + QualType BaseType = BaseExprType; if (IsArrow) { assert(BaseType->isPointerType()); @@ -1040,6 +1008,11 @@ Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType, } R.setBaseObjectType(BaseType); + assert((SS.isEmpty() + ? !BaseType->isDependentType() || computeDeclContext(BaseType) + : !isDependentScopeSpecifier(SS) || computeDeclContext(SS)) && + "dependent lookup context that isn't the current instantiation?"); + // C++1z [expr.ref]p2: // For the first option (dot) the first expression shall be a glvalue [...] if (!IsArrow && BaseExpr && BaseExpr->isPRValue()) { @@ -1068,40 +1041,39 @@ Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType, << isa(FD); if (R.empty()) { - // Rederive where we looked up. - DeclContext *DC = (SS.isSet() - ? computeDeclContext(SS, false) - : BaseType->castAs()->getDecl()); - - if (ExtraArgs) { - ExprResult RetryExpr; - if (!IsArrow && BaseExpr) { - SFINAETrap Trap(*this, true); - ParsedType ObjectType; - bool MayBePseudoDestructor = false; - RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr, - OpLoc, tok::arrow, ObjectType, - MayBePseudoDestructor); - if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) { - CXXScopeSpec TempSS(SS); - RetryExpr = ActOnMemberAccessExpr( - ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS, - TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl); - } - if (Trap.hasErrorOccurred()) - RetryExpr = ExprError(); - } - if (RetryExpr.isUsable()) { - Diag(OpLoc, diag::err_no_member_overloaded_arrow) - << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->"); - return RetryExpr; + ExprResult RetryExpr = ExprError(); + if (ExtraArgs && !IsArrow && BaseExpr && !BaseExpr->isTypeDependent()) { + SFINAETrap Trap(*this, true); + ParsedType ObjectType; + bool MayBePseudoDestructor = false; + RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr, OpLoc, + tok::arrow, ObjectType, + MayBePseudoDestructor); + if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) { + CXXScopeSpec TempSS(SS); + RetryExpr = ActOnMemberAccessExpr( + ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS, + TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl); } + if (Trap.hasErrorOccurred()) + RetryExpr = ExprError(); } - Diag(R.getNameLoc(), diag::err_no_member) - << MemberName << DC - << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange()); - return ExprError(); + // Rederive where we looked up. + DeclContext *DC = + (SS.isSet() ? computeDeclContext(SS) : computeDeclContext(BaseType)); + assert(DC); + + if (RetryExpr.isUsable()) + Diag(OpLoc, diag::err_no_member_overloaded_arrow) + << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->"); + else + Diag(R.getNameLoc(), diag::err_no_member) + << MemberName << DC + << (SS.isSet() + ? SS.getRange() + : (BaseExpr ? BaseExpr->getSourceRange() : SourceRange())); + return RetryExpr; } // Diagnose lookups that find only declarations from a non-base @@ -1186,7 +1158,8 @@ Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType, OpLoc); if (VarDecl *Var = dyn_cast(MemberDecl)) { - return BuildMemberExpr(BaseExpr, IsArrow, OpLoc, &SS, TemplateKWLoc, Var, + return BuildMemberExpr(BaseExpr, IsArrow, OpLoc, + SS.getWithLocInContext(Context), TemplateKWLoc, Var, FoundDecl, /*HadMultipleCandidates=*/false, MemberNameInfo, Var->getType().getNonReferenceType(), VK_LValue, OK_Ordinary); @@ -1203,17 +1176,18 @@ Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType, type = MemberFn->getType(); } - return BuildMemberExpr(BaseExpr, IsArrow, OpLoc, &SS, TemplateKWLoc, + return BuildMemberExpr(BaseExpr, IsArrow, OpLoc, + SS.getWithLocInContext(Context), TemplateKWLoc, MemberFn, FoundDecl, /*HadMultipleCandidates=*/false, MemberNameInfo, type, valueKind, OK_Ordinary); } assert(!isa(MemberDecl) && "member function not C++ method?"); if (EnumConstantDecl *Enum = dyn_cast(MemberDecl)) { - return BuildMemberExpr(BaseExpr, IsArrow, OpLoc, &SS, TemplateKWLoc, Enum, - FoundDecl, /*HadMultipleCandidates=*/false, - MemberNameInfo, Enum->getType(), VK_PRValue, - OK_Ordinary); + return BuildMemberExpr( + BaseExpr, IsArrow, OpLoc, SS.getWithLocInContext(Context), + TemplateKWLoc, Enum, FoundDecl, /*HadMultipleCandidates=*/false, + MemberNameInfo, Enum->getType(), VK_PRValue, OK_Ordinary); } if (VarTemplateDecl *VarTempl = dyn_cast(MemberDecl)) { @@ -1237,7 +1211,8 @@ Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType, if (!Var->getTemplateSpecializationKind()) Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation, MemberLoc); - return BuildMemberExpr(BaseExpr, IsArrow, OpLoc, &SS, TemplateKWLoc, Var, + return BuildMemberExpr(BaseExpr, IsArrow, OpLoc, + SS.getWithLocInContext(Context), TemplateKWLoc, Var, FoundDecl, /*HadMultipleCandidates=*/false, MemberNameInfo, Var->getType().getNonReferenceType(), VK_LValue, OK_Ordinary, TemplateArgs); @@ -1330,7 +1305,6 @@ static ExprResult LookupMemberExpr(Sema &S, LookupResult &R, return ExprError(); QualType BaseType = BaseExpr.get()->getType(); - assert(!BaseType->isDependentType()); DeclarationName MemberName = R.getLookupName(); SourceLocation MemberLoc = R.getNameLoc(); @@ -1342,29 +1316,31 @@ static ExprResult LookupMemberExpr(Sema &S, LookupResult &R, if (IsArrow) { if (const PointerType *Ptr = BaseType->getAs()) BaseType = Ptr->getPointeeType(); - else if (const ObjCObjectPointerType *Ptr - = BaseType->getAs()) + else if (const ObjCObjectPointerType *Ptr = + BaseType->getAs()) BaseType = Ptr->getPointeeType(); - else if (BaseType->isRecordType()) { - // Recover from arrow accesses to records, e.g.: - // struct MyRecord foo; - // foo->bar - // This is actually well-formed in C++ if MyRecord has an - // overloaded operator->, but that should have been dealt with - // by now--or a diagnostic message already issued if a problem - // was encountered while looking for the overloaded operator->. - if (!S.getLangOpts().CPlusPlus) { - S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) - << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange() - << FixItHint::CreateReplacement(OpLoc, "."); + else if (!BaseType->isDependentType()) { + if (BaseType->isRecordType()) { + // Recover from arrow accesses to records, e.g.: + // struct MyRecord foo; + // foo->bar + // This is actually well-formed in C++ if MyRecord has an + // overloaded operator->, but that should have been dealt with + // by now--or a diagnostic message already issued if a problem + // was encountered while looking for the overloaded operator->. + if (!S.getLangOpts().CPlusPlus) { + S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) + << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange() + << FixItHint::CreateReplacement(OpLoc, "."); + } + IsArrow = false; + } else if (BaseType->isFunctionType()) { + goto fail; + } else { + S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow) + << BaseType << BaseExpr.get()->getSourceRange(); + return ExprError(); } - IsArrow = false; - } else if (BaseType->isFunctionType()) { - goto fail; - } else { - S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow) - << BaseType << BaseExpr.get()->getSourceRange(); - return ExprError(); } } @@ -1384,10 +1360,10 @@ static ExprResult LookupMemberExpr(Sema &S, LookupResult &R, } // Handle field access to simple records. - if (const RecordType *RTy = BaseType->getAs()) { + if (BaseType->getAsRecordDecl() || BaseType->isDependentType()) { TypoExpr *TE = nullptr; - if (LookupMemberExprInRecord(S, R, BaseExpr.get(), RTy, OpLoc, IsArrow, SS, - HasTemplateArgs, TemplateKWLoc, TE)) + if (LookupMemberExprInRecord(S, R, BaseExpr.get(), BaseType, OpLoc, IsArrow, + SS, HasTemplateArgs, TemplateKWLoc, TE)) return ExprError(); // Returning valid-but-null is how we indicate to the caller that @@ -1810,7 +1786,6 @@ ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base, DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); - DeclarationName Name = NameInfo.getName(); bool IsArrow = (OpKind == tok::arrow); if (getLangOpts().HLSL && IsArrow) @@ -1824,13 +1799,6 @@ ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base, if (Result.isInvalid()) return ExprError(); Base = Result.get(); - if (Base->getType()->isDependentType() || Name.isDependentName() || - isDependentScopeSpecifier(SS)) { - return ActOnDependentMemberExpr(Base, Base->getType(), IsArrow, OpLoc, SS, - TemplateKWLoc, FirstQualifierInScope, - NameInfo, TemplateArgs); - } - ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl}; ExprResult Res = BuildMemberReferenceExpr( Base, Base->getType(), OpLoc, IsArrow, SS, TemplateKWLoc, @@ -1949,10 +1917,10 @@ Sema::BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, } } - return BuildMemberExpr(Base.get(), IsArrow, OpLoc, &SS, - /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl, - /*HadMultipleCandidates=*/false, MemberNameInfo, - MemberType, VK, OK); + return BuildMemberExpr( + Base.get(), IsArrow, OpLoc, SS.getWithLocInContext(Context), + /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl, + /*HadMultipleCandidates=*/false, MemberNameInfo, MemberType, VK, OK); } /// Builds an implicit member access expression. The current context diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp index 003a157990d307b43b5dc0a252f73c2004a148a7..7d9eaf6720461d2e4f9c746a7f09485c8e48b965 100644 --- a/clang/lib/Sema/SemaInit.cpp +++ b/clang/lib/Sema/SemaInit.cpp @@ -8340,8 +8340,17 @@ void Sema::checkInitializerLifetime(const InitializedEntity &Entity, << Entity.getType()->isReferenceType() << CLE->getInitializer() << 2 << DiagRange; } else { - Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref) - << Entity.getType()->isReferenceType() << DiagRange; + // P2748R5: Disallow Binding a Returned Glvalue to a Temporary. + // [stmt.return]/p6: In a function whose return type is a reference, + // other than an invented function for std::is_convertible ([meta.rel]), + // a return statement that binds the returned reference to a temporary + // expression ([class.temporary]) is ill-formed. + if (getLangOpts().CPlusPlus26 && Entity.getType()->isReferenceType()) + Diag(DiagLoc, diag::err_ret_local_temp_ref) + << Entity.getType()->isReferenceType() << DiagRange; + else + Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref) + << Entity.getType()->isReferenceType() << DiagRange; } break; } @@ -10790,8 +10799,6 @@ QualType Sema::DeduceTemplateSpecializationFromInitializer( // FIXME: Perform "exact type" matching first, per CWG discussion? // Or implement this via an implied 'T(T) -> T' deduction guide? - // FIXME: Do we need/want a std::initializer_list special case? - // Look up deduction guides, including those synthesized from constructors. // // C++1z [over.match.class.deduct]p1: diff --git a/clang/lib/Sema/SemaLookup.cpp b/clang/lib/Sema/SemaLookup.cpp index 55af414df39f51f6b2b1176626cbcc38941f1207..2f6ad49fc08b61557b251630b5f182e9d2c227fb 100644 --- a/clang/lib/Sema/SemaLookup.cpp +++ b/clang/lib/Sema/SemaLookup.cpp @@ -1282,6 +1282,31 @@ bool Sema::CppLookupName(LookupResult &R, Scope *S) { if (DeclContext *DC = PreS->getEntity()) DeclareImplicitMemberFunctionsWithName(*this, Name, R.getNameLoc(), DC); } + // C++23 [temp.dep.general]p2: + // The component name of an unqualified-id is dependent if + // - it is a conversion-function-id whose conversion-type-id + // is dependent, or + // - it is operator= and the current class is a templated entity, or + // - the unqualified-id is the postfix-expression in a dependent call. + if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && + Name.getCXXNameType()->isDependentType()) { + R.setNotFoundInCurrentInstantiation(); + return false; + } + + // If this is the name of an implicitly-declared special member function, + // go through the scope stack to implicitly declare + if (isImplicitlyDeclaredMemberFunctionName(Name)) { + for (Scope *PreS = S; PreS; PreS = PreS->getParent()) + if (DeclContext *DC = PreS->getEntity()) { + if (DC->isDependentContext() && isa(DC) && + Name.getCXXOverloadedOperator() == OO_Equal) { + R.setNotFoundInCurrentInstantiation(); + return false; + } + DeclareImplicitMemberFunctionsWithName(*this, Name, R.getNameLoc(), DC); + } + } // Implicitly declare member functions with the name we're looking for, if in // fact we are in a scope where it matters. @@ -2446,10 +2471,33 @@ bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, } } QL(LookupCtx); + CXXRecordDecl *LookupRec = dyn_cast(LookupCtx); + // FIXME: Per [temp.dep.general]p2, an unqualified name is also dependent + // if it's a dependent conversion-function-id or operator= where the current + // class is a templated entity. This should be handled in LookupName. + if (!InUnqualifiedLookup && !R.isForRedeclaration()) { + // C++23 [temp.dep.type]p5: + // A qualified name is dependent if + // - it is a conversion-function-id whose conversion-type-id + // is dependent, or + // - [...] + // - its lookup context is the current instantiation and it + // is operator=, or + // - [...] + if (DeclarationName Name = R.getLookupName(); + (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && + Name.getCXXNameType()->isDependentType()) || + (Name.getCXXOverloadedOperator() == OO_Equal && LookupRec && + LookupRec->isDependentContext())) { + R.setNotFoundInCurrentInstantiation(); + return false; + } + } + if (LookupDirect(*this, R, LookupCtx)) { R.resolveKind(); - if (isa(LookupCtx)) - R.setNamingClass(cast(LookupCtx)); + if (LookupRec) + R.setNamingClass(LookupRec); return true; } @@ -2471,7 +2519,6 @@ bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, // If this isn't a C++ class, we aren't allowed to look into base // classes, we're done. - CXXRecordDecl *LookupRec = dyn_cast(LookupCtx); if (!LookupRec || !LookupRec->getDefinition()) return false; @@ -2718,38 +2765,54 @@ bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, /// /// @returns True if any decls were found (but possibly ambiguous) bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, - bool AllowBuiltinCreation, bool EnteringContext) { - if (SS && SS->isInvalid()) { - // When the scope specifier is invalid, don't even look for - // anything. + QualType ObjectType, bool AllowBuiltinCreation, + bool EnteringContext) { + // When the scope specifier is invalid, don't even look for anything. + if (SS && SS->isInvalid()) return false; - } - if (SS && SS->isSet()) { - NestedNameSpecifier *NNS = SS->getScopeRep(); - if (NNS->getKind() == NestedNameSpecifier::Super) + // Determine where to perform name lookup + DeclContext *DC = nullptr; + bool IsDependent = false; + if (!ObjectType.isNull()) { + // This nested-name-specifier occurs in a member access expression, e.g., + // x->B::f, and we are looking into the type of the object. + assert((!SS || SS->isEmpty()) && + "ObjectType and scope specifier cannot coexist"); + DC = computeDeclContext(ObjectType); + IsDependent = !DC && ObjectType->isDependentType(); + assert(((!DC && ObjectType->isDependentType()) || + !ObjectType->isIncompleteType() || !ObjectType->getAs() || + ObjectType->castAs()->isBeingDefined()) && + "Caller should have completed object type"); + } else if (SS && SS->isNotEmpty()) { + if (NestedNameSpecifier *NNS = SS->getScopeRep(); + NNS->getKind() == NestedNameSpecifier::Super) return LookupInSuper(R, NNS->getAsRecordDecl()); - - if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) { - // We have resolved the scope specifier to a particular declaration - // contex, and will perform name lookup in that context. + // This nested-name-specifier occurs after another nested-name-specifier, + // so long into the context associated with the prior nested-name-specifier. + if ((DC = computeDeclContext(*SS, EnteringContext))) { + // The declaration context must be complete. if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC)) return false; - R.setContextRange(SS->getRange()); - return LookupQualifiedName(R, DC); } + IsDependent = !DC && isDependentScopeSpecifier(*SS); + } else { + // Perform unqualified name lookup starting in the given scope. + return LookupName(R, S, AllowBuiltinCreation); + } + // If we were able to compute a declaration context, perform qualified name + // lookup in that context. + if (DC) + return LookupQualifiedName(R, DC); + else if (IsDependent) // We could not resolve the scope specified to a specific declaration // context, which means that SS refers to an unknown specialization. // Name lookup can't find anything in this case. R.setNotFoundInCurrentInstantiation(); - R.setContextRange(SS->getRange()); - return false; - } - - // Perform unqualified name lookup starting in the given scope. - return LookupName(R, S, AllowBuiltinCreation); + return false; } /// Perform qualified name lookup into all base classes of the given @@ -5018,8 +5081,9 @@ static void LookupPotentialTypoResult(Sema &SemaRef, return; } - SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false, - EnteringContext); + SemaRef.LookupParsedName(Res, S, SS, + /*ObjectType=*/QualType(), + /*AllowBuiltinCreation=*/false, EnteringContext); // Fake ivar lookup; this should really be part of // LookupParsedName. diff --git a/clang/lib/Sema/SemaOpenACC.cpp b/clang/lib/Sema/SemaOpenACC.cpp index d5cfe82a5d70980dd93cadc8a3678cb50528d64a..3ea81e0497c2032558756c67cb7b5878f2a8816b 100644 --- a/clang/lib/Sema/SemaOpenACC.cpp +++ b/clang/lib/Sema/SemaOpenACC.cpp @@ -103,6 +103,18 @@ bool doesClauseApplyToDirective(OpenACCDirectiveKind DirectiveKind, default: return false; } + case OpenACCClauseKind::Private: + switch (DirectiveKind) { + case OpenACCDirectiveKind::Parallel: + case OpenACCDirectiveKind::Serial: + case OpenACCDirectiveKind::Loop: + case OpenACCDirectiveKind::ParallelLoop: + case OpenACCDirectiveKind::SerialLoop: + case OpenACCDirectiveKind::KernelsLoop: + return true; + default: + return false; + } default: // Do nothing so we can go to the 'unimplemented' diagnostic instead. return true; @@ -303,6 +315,21 @@ SemaOpenACC::ActOnClause(ArrayRef ExistingClauses, getASTContext(), Clause.getBeginLoc(), Clause.getLParenLoc(), Clause.getIntExprs()[0], Clause.getEndLoc()); } + case OpenACCClauseKind::Private: { + // Restrictions only properly implemented on 'compute' constructs, and + // 'compute' constructs are the only construct that can do anything with + // this yet, so skip/treat as unimplemented in this case. + if (!isOpenACCComputeDirectiveKind(Clause.getDirectiveKind())) + break; + + // ActOnVar ensured that everything is a valid variable reference, so there + // really isn't anything to do here. GCC does some duplicate-finding, though + // it isn't apparent in the standard where this is justified. + + return OpenACCPrivateClause::Create( + getASTContext(), Clause.getBeginLoc(), Clause.getLParenLoc(), + Clause.getVarList(), Clause.getEndLoc()); + } default: break; } @@ -423,6 +450,52 @@ ExprResult SemaOpenACC::ActOnIntExpr(OpenACCDirectiveKind DK, return IntExpr; } +ExprResult SemaOpenACC::ActOnVar(Expr *VarExpr) { + // We still need to retain the array subscript/subarray exprs, so work on a + // copy. + Expr *CurVarExpr = VarExpr->IgnoreParenImpCasts(); + + // Sub-arrays/subscript-exprs are fine as long as the base is a + // VarExpr/MemberExpr. So strip all of those off. + while (isa(CurVarExpr)) { + if (auto *SubScrpt = dyn_cast(CurVarExpr)) + CurVarExpr = SubScrpt->getBase()->IgnoreParenImpCasts(); + else + CurVarExpr = + cast(CurVarExpr)->getBase()->IgnoreParenImpCasts(); + } + + // References to a VarDecl are fine. + if (const auto *DRE = dyn_cast(CurVarExpr)) { + if (isa( + DRE->getDecl()->getCanonicalDecl())) + return VarExpr; + } + + // A MemberExpr that references a Field is valid. + if (const auto *ME = dyn_cast(CurVarExpr)) { + if (isa(ME->getMemberDecl()->getCanonicalDecl())) + return VarExpr; + } + + // Referring to 'this' is always OK. + if (isa(CurVarExpr)) + return VarExpr; + + // Nothing really we can do here, as these are dependent. So just return they + // are valid. + if (isa(CurVarExpr)) + return VarExpr; + + // There isn't really anything we can do in the case of a recovery expr, so + // skip the diagnostic rather than produce a confusing diagnostic. + if (isa(CurVarExpr)) + return ExprError(); + + Diag(VarExpr->getExprLoc(), diag::err_acc_not_a_var_ref); + return ExprError(); +} + ExprResult SemaOpenACC::ActOnArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLoc, diff --git a/clang/lib/Sema/SemaOpenMP.cpp b/clang/lib/Sema/SemaOpenMP.cpp index cee8da495c549566de34ccff6973ccb6b7f2c5e4..cf5447f223d450fc6f2c730c868c058652ead285 100644 --- a/clang/lib/Sema/SemaOpenMP.cpp +++ b/clang/lib/Sema/SemaOpenMP.cpp @@ -3061,7 +3061,9 @@ ExprResult SemaOpenMP::ActOnOpenMPIdExpression(Scope *CurScope, OpenMPDirectiveKind Kind) { ASTContext &Context = getASTContext(); LookupResult Lookup(SemaRef, Id, Sema::LookupOrdinaryName); - SemaRef.LookupParsedName(Lookup, CurScope, &ScopeSpec, true); + SemaRef.LookupParsedName(Lookup, CurScope, &ScopeSpec, + /*ObjectType=*/QualType(), + /*AllowBuiltinCreation=*/true); if (Lookup.isAmbiguous()) return ExprError(); @@ -7407,7 +7409,8 @@ void SemaOpenMP::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( const IdentifierInfo *BaseII = D.getIdentifier(); LookupResult Lookup(SemaRef, DeclarationName(BaseII), D.getIdentifierLoc(), Sema::LookupOrdinaryName); - SemaRef.LookupParsedName(Lookup, S, &D.getCXXScopeSpec()); + SemaRef.LookupParsedName(Lookup, S, &D.getCXXScopeSpec(), + /*ObjectType=*/QualType()); TypeSourceInfo *TInfo = SemaRef.GetTypeForDeclarator(D); QualType FType = TInfo->getType(); @@ -19311,7 +19314,8 @@ buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, if (S) { LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); Lookup.suppressDiagnostics(); - while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { + while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec, + /*ObjectType=*/QualType())) { NamedDecl *D = Lookup.getRepresentativeDecl(); do { S = S->getParent(); @@ -22180,7 +22184,8 @@ static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S, LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName); Lookup.suppressDiagnostics(); if (S) { - while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) { + while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec, + /*ObjectType=*/QualType())) { NamedDecl *D = Lookup.getRepresentativeDecl(); while (S && !S->isDeclScope(D)) S = S->getParent(); @@ -23497,7 +23502,9 @@ void SemaOpenMP::DiagnoseUnterminatedOpenMPDeclareTarget() { NamedDecl *SemaOpenMP::lookupOpenMPDeclareTargetName( Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id) { LookupResult Lookup(SemaRef, Id, Sema::LookupOrdinaryName); - SemaRef.LookupParsedName(Lookup, CurScope, &ScopeSpec, true); + SemaRef.LookupParsedName(Lookup, CurScope, &ScopeSpec, + /*ObjectType=*/QualType(), + /*AllowBuiltinCreation=*/true); if (Lookup.isAmbiguous()) return nullptr; diff --git a/clang/lib/Sema/SemaStmtAttr.cpp b/clang/lib/Sema/SemaStmtAttr.cpp index 9d44c22c8ddcc3a234c46af72b16d19e96829d4f..1c84830b6ddd2e6de81be299fb907a8a5eb78c1e 100644 --- a/clang/lib/Sema/SemaStmtAttr.cpp +++ b/clang/lib/Sema/SemaStmtAttr.cpp @@ -109,16 +109,14 @@ static Attr *handleLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A, SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable); } else if (PragmaName == "unroll") { // #pragma unroll N - if (ValueExpr && !ValueExpr->isValueDependent()) { - llvm::APSInt ValueAPS; - ExprResult R = S.VerifyIntegerConstantExpression(ValueExpr, &ValueAPS); - assert(!R.isInvalid() && "unroll count value must be a valid value, it's " - "should be checked in Sema::CheckLoopHintExpr"); - (void)R; - // The values of 0 and 1 block any unrolling of the loop. - if (ValueAPS.isZero() || ValueAPS.isOne()) - SetHints(LoopHintAttr::UnrollCount, LoopHintAttr::Disable); - else + if (ValueExpr) { + if (!ValueExpr->isValueDependent()) { + auto Value = ValueExpr->EvaluateKnownConstInt(S.getASTContext()); + if (Value.isZero() || Value.isOne()) + SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable); + else + SetHints(LoopHintAttr::UnrollCount, LoopHintAttr::Numeric); + } else SetHints(LoopHintAttr::UnrollCount, LoopHintAttr::Numeric); } else SetHints(LoopHintAttr::Unroll, LoopHintAttr::Enable); diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp index bbcb7c33a985793bd8331e5e3ed5a49cd3b789e6..7f18631c6096d1b04a62c05fa42b8e933818238c 100644 --- a/clang/lib/Sema/SemaTemplate.cpp +++ b/clang/lib/Sema/SemaTemplate.cpp @@ -210,10 +210,11 @@ TemplateNameKind Sema::isTemplateName(Scope *S, AssumedTemplateKind AssumedTemplate; LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName); if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext, - MemberOfUnknownSpecialization, SourceLocation(), + /*RequiredTemplate=*/SourceLocation(), &AssumedTemplate, /*AllowTypoCorrection=*/!Disambiguation)) return TNK_Non_template; + MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation(); if (AssumedTemplate != AssumedTemplateKind::None) { TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName)); @@ -320,15 +321,12 @@ TemplateNameKind Sema::isTemplateName(Scope *S, bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, CXXScopeSpec &SS, ParsedTemplateTy *Template /*=nullptr*/) { - bool MemberOfUnknownSpecialization = false; - // We could use redeclaration lookup here, but we don't need to: the // syntactic form of a deduction guide is enough to identify it even // if we can't look up the template name at all. LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName); if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(), - /*EnteringContext*/ false, - MemberOfUnknownSpecialization)) + /*EnteringContext*/ false)) return false; if (R.empty()) return false; @@ -374,11 +372,8 @@ bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II, return true; } -bool Sema::LookupTemplateName(LookupResult &Found, - Scope *S, CXXScopeSpec &SS, - QualType ObjectType, - bool EnteringContext, - bool &MemberOfUnknownSpecialization, +bool Sema::LookupTemplateName(LookupResult &Found, Scope *S, CXXScopeSpec &SS, + QualType ObjectType, bool EnteringContext, RequiredTemplateKind RequiredTemplate, AssumedTemplateKind *ATK, bool AllowTypoCorrection) { @@ -391,7 +386,6 @@ bool Sema::LookupTemplateName(LookupResult &Found, Found.setTemplateNameLookup(true); // Determine where to perform name lookup - MemberOfUnknownSpecialization = false; DeclContext *LookupCtx = nullptr; bool IsDependent = false; if (!ObjectType.isNull()) { @@ -548,7 +542,7 @@ bool Sema::LookupTemplateName(LookupResult &Found, FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup); if (Found.empty()) { if (IsDependent) { - MemberOfUnknownSpecialization = true; + Found.setNotFoundInCurrentInstantiation(); return false; } @@ -5595,11 +5589,9 @@ Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, RequireCompleteDeclContext(SS, DC)) return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs); - bool MemberOfUnknownSpecialization; LookupResult R(*this, NameInfo, LookupOrdinaryName); if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(), - /*Entering*/false, MemberOfUnknownSpecialization, - TemplateKWLoc)) + /*Entering*/ false, TemplateKWLoc)) return ExprError(); if (R.isAmbiguous()) @@ -5720,14 +5712,13 @@ TemplateNameKind Sema::ActOnTemplateName(Scope *S, DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name); LookupResult R(*this, DNI.getName(), Name.getBeginLoc(), LookupOrdinaryName); - bool MOUS; // Tell LookupTemplateName that we require a template so that it diagnoses // cases where it finds a non-template. RequiredTemplateKind RTK = TemplateKWLoc.isValid() ? RequiredTemplateKind(TemplateKWLoc) : TemplateNameIsRequired; - if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, MOUS, - RTK, nullptr, /*AllowTypoCorrection=*/false) && + if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK, + /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) && !R.isAmbiguous()) { if (LookupCtx) Diag(Name.getBeginLoc(), diag::err_no_member) @@ -5816,7 +5807,7 @@ bool Sema::CheckTemplateTypeArgument( if (auto *II = NameInfo.getName().getAsIdentifierInfo()) { LookupResult Result(*this, NameInfo, LookupOrdinaryName); - LookupParsedName(Result, CurScope, &SS); + LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType()); if (Result.getAsSingle() || Result.getResultKind() == @@ -7706,7 +7697,7 @@ ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param, // FIXME: The language rules don't say what happens in this case. // FIXME: We get an opaque dependent type out of decltype(auto) if the // expression is merely instantiation-dependent; is this enough? - if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) { + if (Arg->isTypeDependent()) { auto *AT = dyn_cast(DeducedT); if (AT && AT->isDecltypeAuto()) { SugaredConverted = TemplateArgument(Arg); @@ -8438,10 +8429,9 @@ void Sema::NoteTemplateParameterLocation(const NamedDecl &Decl) { /// declaration and the type of its corresponding non-type template /// parameter, produce an expression that properly refers to that /// declaration. -ExprResult -Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, - QualType ParamType, - SourceLocation Loc) { +ExprResult Sema::BuildExpressionFromDeclTemplateArgument( + const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc, + NamedDecl *TemplateParam) { // C++ [temp.param]p8: // // A non-type template-parameter of type "array of T" or @@ -8508,6 +8498,18 @@ Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, } else { assert(ParamType->isReferenceType() && "unexpected type for decl template argument"); + if (NonTypeTemplateParmDecl *NTTP = + dyn_cast_if_present(TemplateParam)) { + QualType TemplateParamType = NTTP->getType(); + const AutoType *AT = TemplateParamType->getAs(); + if (AT && AT->isDecltypeAuto()) { + RefExpr = new (getASTContext()) SubstNonTypeTemplateParmExpr( + ParamType->getPointeeType(), RefExpr.get()->getValueKind(), + RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(), + /*PackIndex=*/std::nullopt, + /*RefParam=*/true); + } + } } // At this point we should have the right value category. @@ -11179,7 +11181,8 @@ DeclResult Sema::ActOnExplicitInstantiation(Scope *S, : TSK_ExplicitInstantiationDeclaration; LookupResult Previous(*this, NameInfo, LookupOrdinaryName); - LookupParsedName(Previous, S, &D.getCXXScopeSpec()); + LookupParsedName(Previous, S, &D.getCXXScopeSpec(), + /*ObjectType=*/QualType()); if (!R->isFunctionType()) { // C++ [temp.explicit]p1: diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp b/clang/lib/Sema/SemaTemplateDeduction.cpp index c3815bca038554bfa1cf76775b1550c55fcbd6c0..e93f7bd842e444754103aae890aa4da60f4bf5e1 100644 --- a/clang/lib/Sema/SemaTemplateDeduction.cpp +++ b/clang/lib/Sema/SemaTemplateDeduction.cpp @@ -2639,7 +2639,8 @@ static bool isSameTemplateArg(ASTContext &Context, /// argument. TemplateArgumentLoc Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, - QualType NTTPType, SourceLocation Loc) { + QualType NTTPType, SourceLocation Loc, + NamedDecl *TemplateParam) { switch (Arg.getKind()) { case TemplateArgument::Null: llvm_unreachable("Can't get a NULL template argument here"); @@ -2651,7 +2652,8 @@ Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, case TemplateArgument::Declaration: { if (NTTPType.isNull()) NTTPType = Arg.getParamTypeForDecl(); - Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc) + Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc, + TemplateParam) .getAs(); return TemplateArgumentLoc(TemplateArgument(E), E); } @@ -2718,8 +2720,8 @@ static bool ConvertDeducedTemplateArgument( // Convert the deduced template argument into a template // argument that we can check, almost as if the user had written // the template argument explicitly. - TemplateArgumentLoc ArgLoc = - S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation()); + TemplateArgumentLoc ArgLoc = S.getTrivialTemplateArgumentLoc( + Arg, QualType(), Info.getLocation(), Param); // Check the template argument, converting it as necessary. return S.CheckTemplateArgument( diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp b/clang/lib/Sema/SemaTemplateInstantiate.cpp index 98d5c7cb3a8a808d203ccd97e07614c5bad7e60d..3a9fd906b7af86ad4d501d0d2f0045739179a5f3 100644 --- a/clang/lib/Sema/SemaTemplateInstantiate.cpp +++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp @@ -2151,13 +2151,25 @@ TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) { // Generate error if there is a problem with the value. if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation(), - LH->getOption() == LoopHintAttr::UnrollCount)) + LH->getSemanticSpelling() == + LoopHintAttr::Pragma_unroll)) return LH; + LoopHintAttr::OptionType Option = LH->getOption(); + LoopHintAttr::LoopHintState State = LH->getState(); + + llvm::APSInt ValueAPS = + TransformedExpr->EvaluateKnownConstInt(getSema().getASTContext()); + // The values of 0 and 1 block any unrolling of the loop. + if (ValueAPS.isZero() || ValueAPS.isOne()) { + Option = LoopHintAttr::Unroll; + State = LoopHintAttr::Disable; + } + // Create new LoopHintValueAttr with integral expression in place of the // non-type template parameter. - return LoopHintAttr::CreateImplicit(getSema().Context, LH->getOption(), - LH->getState(), TransformedExpr, *LH); + return LoopHintAttr::CreateImplicit(getSema().Context, Option, State, + TransformedExpr, *LH); } const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr( const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) { diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h index f47bc219e6fa32b2368c7b0338c96779f17ec98b..dff7e9df636b966b2627572e2b2bc6d155f687eb 100644 --- a/clang/lib/Sema/TreeTransform.h +++ b/clang/lib/Sema/TreeTransform.h @@ -6657,6 +6657,10 @@ TreeTransform::TransformPackIndexingType(TypeLocBuilder &TLB, } } + // A pack indexing type can appear in a larger pack expansion, + // e.g. `Pack...[pack_of_indexes]...` + // so we need to temporarily disable substitution of pack elements + Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1); QualType Result = getDerived().TransformType(TLB, TL.getPatternLoc()); QualType Out = getDerived().RebuildPackIndexingType( @@ -11104,13 +11108,15 @@ template class OpenACCClauseTransform final : public OpenACCClauseVisitor> { TreeTransform &Self; + ArrayRef ExistingClauses; SemaOpenACC::OpenACCParsedClause &ParsedClause; OpenACCClause *NewClause = nullptr; public: OpenACCClauseTransform(TreeTransform &Self, + ArrayRef ExistingClauses, SemaOpenACC::OpenACCParsedClause &PC) - : Self(Self), ParsedClause(PC) {} + : Self(Self), ExistingClauses(ExistingClauses), ParsedClause(PC) {} OpenACCClause *CreatedClause() const { return NewClause; } @@ -11196,6 +11202,31 @@ void OpenACCClauseTransform::VisitNumGangsClause( ParsedClause.getLParenLoc(), ParsedClause.getIntExprs(), ParsedClause.getEndLoc()); } + +template +void OpenACCClauseTransform::VisitPrivateClause( + const OpenACCPrivateClause &C) { + llvm::SmallVector InstantiatedVarList; + + for (Expr *CurVar : C.getVarList()) { + ExprResult Res = Self.TransformExpr(CurVar); + + if (!Res.isUsable()) + return; + + Res = Self.getSema().OpenACC().ActOnVar(Res.get()); + + if (Res.isUsable()) + InstantiatedVarList.push_back(Res.get()); + } + ParsedClause.setVarListDetails(std::move(InstantiatedVarList)); + + NewClause = OpenACCPrivateClause::Create( + Self.getSema().getASTContext(), ParsedClause.getBeginLoc(), + ParsedClause.getLParenLoc(), ParsedClause.getVarList(), + ParsedClause.getEndLoc()); +} + template void OpenACCClauseTransform::VisitNumWorkersClause( const OpenACCNumWorkersClause &C) { @@ -11254,7 +11285,8 @@ OpenACCClause *TreeTransform::TransformOpenACCClause( if (const auto *WithParms = dyn_cast(OldClause)) ParsedClause.setLParenLoc(WithParms->getLParenLoc()); - OpenACCClauseTransform Transform{*this, ParsedClause}; + OpenACCClauseTransform Transform{*this, ExistingClauses, + ParsedClause}; Transform.Visit(OldClause); return Transform.CreatedClause(); @@ -13217,6 +13249,26 @@ bool TreeTransform::TransformOverloadExprDecls(OverloadExpr *Old, // Resolve a kind, but don't do any further analysis. If it's // ambiguous, the callee needs to deal with it. R.resolveKind(); + + if (Old->hasTemplateKeyword() && !R.empty()) { + NamedDecl *FoundDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); + getSema().FilterAcceptableTemplateNames(R, + /*AllowFunctionTemplates=*/true, + /*AllowDependent=*/true); + if (R.empty()) { + // If a 'template' keyword was used, a lookup that finds only non-template + // names is an error. + getSema().Diag(R.getNameLoc(), + diag::err_template_kw_refers_to_non_template) + << R.getLookupName() << Old->getQualifierLoc().getSourceRange() + << Old->hasTemplateKeyword() << Old->getTemplateKeywordLoc(); + getSema().Diag(FoundDecl->getLocation(), + diag::note_template_kw_refers_to_non_template) + << R.getLookupName(); + return true; + } + } + return false; } diff --git a/clang/lib/Serialization/ASTReader.cpp b/clang/lib/Serialization/ASTReader.cpp index 0ef57a3ea804efcaa9e513e273e8a6b4fab2b4af..29b81c1a753cf563e9f4e9361ec007b5dc108ea9 100644 --- a/clang/lib/Serialization/ASTReader.cpp +++ b/clang/lib/Serialization/ASTReader.cpp @@ -2630,6 +2630,14 @@ InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) { F.StandardCXXModule && FileChange.Kind == Change::None) FileChange = HasInputContentChanged(FileChange); + // When we have StoredTime equal to zero and ValidateASTInputFilesContent, + // it is better to check the content of the input files because we cannot rely + // on the file modification time, which will be the same (zero) for these + // files. + if (!StoredTime && ValidateASTInputFilesContent && + FileChange.Kind == Change::None) + FileChange = HasInputContentChanged(FileChange); + // For an overridden file, there is nothing to validate. if (!Overridden && FileChange.Kind != Change::None) { if (Complain && !Diags.isDiagnosticInFlight()) { @@ -11768,6 +11776,14 @@ void ASTRecordReader::readOMPChildren(OMPChildren *Data) { Data->getChildren()[I] = readStmt(); } +SmallVector ASTRecordReader::readOpenACCVarList() { + unsigned NumVars = readInt(); + llvm::SmallVector VarList; + for (unsigned I = 0; I < NumVars; ++I) + VarList.push_back(readSubExpr()); + return VarList; +} + OpenACCClause *ASTRecordReader::readOpenACCClause() { OpenACCClauseKind ClauseKind = readEnum(); SourceLocation BeginLoc = readSourceLocation(); @@ -11813,6 +11829,12 @@ OpenACCClause *ASTRecordReader::readOpenACCClause() { return OpenACCVectorLengthClause::Create(getContext(), BeginLoc, LParenLoc, IntExpr, EndLoc); } + case OpenACCClauseKind::Private: { + SourceLocation LParenLoc = readSourceLocation(); + llvm::SmallVector VarList = readOpenACCVarList(); + return OpenACCPrivateClause::Create(getContext(), BeginLoc, LParenLoc, + VarList, EndLoc); + } case OpenACCClauseKind::Finalize: case OpenACCClauseKind::IfPresent: case OpenACCClauseKind::Seq: @@ -11834,7 +11856,6 @@ OpenACCClause *ASTRecordReader::readOpenACCClause() { case OpenACCClauseKind::Link: case OpenACCClauseKind::NoCreate: case OpenACCClauseKind::Present: - case OpenACCClauseKind::Private: case OpenACCClauseKind::CopyOut: case OpenACCClauseKind::CopyIn: case OpenACCClauseKind::Create: diff --git a/clang/lib/Serialization/ASTWriter.cpp b/clang/lib/Serialization/ASTWriter.cpp index 0408eeb6a95b0075d7a1c23b7be299d653bccf52..80c7ce643088b63ad549b4537aa666b69b236b33 100644 --- a/clang/lib/Serialization/ASTWriter.cpp +++ b/clang/lib/Serialization/ASTWriter.cpp @@ -173,54 +173,50 @@ GetAffectingModuleMaps(const Preprocessor &PP, Module *RootModule) { const HeaderSearch &HS = PP.getHeaderSearchInfo(); const ModuleMap &MM = HS.getModuleMap(); - const SourceManager &SourceMgr = PP.getSourceManager(); std::set ModuleMaps; - auto CollectIncludingModuleMaps = [&](FileID FID, FileEntryRef F) { - if (!ModuleMaps.insert(F).second) + std::set ProcessedModules; + auto CollectModuleMapsForHierarchy = [&](const Module *M) { + M = M->getTopLevelModule(); + + if (!ProcessedModules.insert(M).second) return; - SourceLocation Loc = SourceMgr.getIncludeLoc(FID); - // The include location of inferred module maps can point into the header - // file that triggered the inferring. Cut off the walk if that's the case. - while (Loc.isValid() && isModuleMap(SourceMgr.getFileCharacteristic(Loc))) { - FID = SourceMgr.getFileID(Loc); - F = *SourceMgr.getFileEntryRefForID(FID); - if (!ModuleMaps.insert(F).second) - break; - Loc = SourceMgr.getIncludeLoc(FID); - } - }; - std::set ProcessedModules; - auto CollectIncludingMapsFromAncestors = [&](const Module *M) { - for (const Module *Mod = M; Mod; Mod = Mod->Parent) { - if (!ProcessedModules.insert(Mod).second) - break; + std::queue Q; + Q.push(M); + while (!Q.empty()) { + const Module *Mod = Q.front(); + Q.pop(); + // The containing module map is affecting, because it's being pointed // into by Module::DefinitionLoc. - if (FileID FID = MM.getContainingModuleMapFileID(Mod); FID.isValid()) - CollectIncludingModuleMaps(FID, *SourceMgr.getFileEntryRefForID(FID)); - // For inferred modules, the module map that allowed inferring is not in - // the include chain of the virtual containing module map file. It did - // affect the compilation, though. - if (FileID FID = MM.getModuleMapFileIDForUniquing(Mod); FID.isValid()) - CollectIncludingModuleMaps(FID, *SourceMgr.getFileEntryRefForID(FID)); + if (auto FE = MM.getContainingModuleMapFile(Mod)) + ModuleMaps.insert(*FE); + // For inferred modules, the module map that allowed inferring is not + // related to the virtual containing module map file. It did affect the + // compilation, though. + if (auto FE = MM.getModuleMapFileForUniquing(Mod)) + ModuleMaps.insert(*FE); + + for (auto *SubM : Mod->submodules()) + Q.push(SubM); } }; // Handle all the affecting modules referenced from the root module. + CollectModuleMapsForHierarchy(RootModule); + std::queue Q; Q.push(RootModule); while (!Q.empty()) { const Module *CurrentModule = Q.front(); Q.pop(); - CollectIncludingMapsFromAncestors(CurrentModule); for (const Module *ImportedModule : CurrentModule->Imports) - CollectIncludingMapsFromAncestors(ImportedModule); + CollectModuleMapsForHierarchy(ImportedModule); for (const Module *UndeclaredModule : CurrentModule->UndeclaredUses) - CollectIncludingMapsFromAncestors(UndeclaredModule); + CollectModuleMapsForHierarchy(UndeclaredModule); for (auto *M : CurrentModule->submodules()) Q.push(M); @@ -249,9 +245,27 @@ GetAffectingModuleMaps(const Preprocessor &PP, Module *RootModule) { for (const auto &KH : HS.findResolvedModulesForHeader(*File)) if (const Module *M = KH.getModule()) - CollectIncludingMapsFromAncestors(M); + CollectModuleMapsForHierarchy(M); } + // FIXME: This algorithm is not correct for module map hierarchies where + // module map file defining a (sub)module of a top-level module X includes + // a module map file that defines a (sub)module of another top-level module Y. + // Whenever X is affecting and Y is not, "replaying" this PCM file will fail + // when parsing module map files for X due to not knowing about the `extern` + // module map for Y. + // + // We don't have a good way to fix it here. We could mark all children of + // affecting module map files as being affecting as well, but that's + // expensive. SourceManager does not model the edge from parent to child + // SLocEntries, so instead, we would need to iterate over leaf module map + // files, walk up their include hierarchy and check whether we arrive at an + // affecting module map. + // + // Instead of complicating and slowing down this function, we should probably + // just ban module map hierarchies where module map defining a (sub)module X + // includes a module map defining a module that's not a submodule of X. + return ModuleMaps; } @@ -1174,26 +1188,47 @@ ASTWriter::createSignature() const { return std::make_pair(ASTBlockHash, Signature); } +ASTFileSignature ASTWriter::createSignatureForNamedModule() const { + llvm::SHA1 Hasher; + Hasher.update(StringRef(Buffer.data(), Buffer.size())); + + assert(WritingModule); + assert(WritingModule->isNamedModule()); + + // We need to combine all the export imported modules no matter + // we used it or not. + for (auto [ExportImported, _] : WritingModule->Exports) + Hasher.update(ExportImported->Signature); + + return ASTFileSignature::create(Hasher.result()); +} + +static void BackpatchSignatureAt(llvm::BitstreamWriter &Stream, + const ASTFileSignature &S, uint64_t BitNo) { + for (uint8_t Byte : S) { + Stream.BackpatchByte(BitNo, Byte); + BitNo += 8; + } +} + ASTFileSignature ASTWriter::backpatchSignature() { + if (isWritingStdCXXNamedModules()) { + ASTFileSignature Signature = createSignatureForNamedModule(); + BackpatchSignatureAt(Stream, Signature, SignatureOffset); + return Signature; + } + if (!WritingModule || !PP->getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent) return {}; // For implicit modules, write the hash of the PCM as its signature. - - auto BackpatchSignatureAt = [&](const ASTFileSignature &S, uint64_t BitNo) { - for (uint8_t Byte : S) { - Stream.BackpatchByte(BitNo, Byte); - BitNo += 8; - } - }; - ASTFileSignature ASTBlockHash; ASTFileSignature Signature; std::tie(ASTBlockHash, Signature) = createSignature(); - BackpatchSignatureAt(ASTBlockHash, ASTBlockHashOffset); - BackpatchSignatureAt(Signature, SignatureOffset); + BackpatchSignatureAt(Stream, ASTBlockHash, ASTBlockHashOffset); + BackpatchSignatureAt(Stream, Signature, SignatureOffset); return Signature; } @@ -1210,9 +1245,11 @@ void ASTWriter::writeUnhashedControlBlock(Preprocessor &PP, RecordData Record; Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5); - // For implicit modules, write the hash of the PCM as its signature. - if (WritingModule && - PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent) { + // For implicit modules and C++20 named modules, write the hash of the PCM as + // its signature. + if (isWritingStdCXXNamedModules() || + (WritingModule && + PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent)) { // At this point, we don't know the actual signature of the file or the AST // block - we're only able to compute those at the end of the serialization // process. Let's store dummy signatures for now, and replace them with the @@ -1223,21 +1260,24 @@ void ASTWriter::writeUnhashedControlBlock(Preprocessor &PP, auto Dummy = ASTFileSignature::createDummy(); SmallString<128> Blob{Dummy.begin(), Dummy.end()}; - auto Abbrev = std::make_shared(); - Abbrev->Add(BitCodeAbbrevOp(AST_BLOCK_HASH)); - Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); - unsigned ASTBlockHashAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); + // We don't need AST Block hash in named modules. + if (!isWritingStdCXXNamedModules()) { + auto Abbrev = std::make_shared(); + Abbrev->Add(BitCodeAbbrevOp(AST_BLOCK_HASH)); + Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); + unsigned ASTBlockHashAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); - Abbrev = std::make_shared(); + Record.push_back(AST_BLOCK_HASH); + Stream.EmitRecordWithBlob(ASTBlockHashAbbrev, Record, Blob); + ASTBlockHashOffset = Stream.GetCurrentBitNo() - Blob.size() * 8; + Record.clear(); + } + + auto Abbrev = std::make_shared(); Abbrev->Add(BitCodeAbbrevOp(SIGNATURE)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); unsigned SignatureAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); - Record.push_back(AST_BLOCK_HASH); - Stream.EmitRecordWithBlob(ASTBlockHashAbbrev, Record, Blob); - ASTBlockHashOffset = Stream.GetCurrentBitNo() - Blob.size() * 8; - Record.clear(); - Record.push_back(SIGNATURE); Stream.EmitRecordWithBlob(SignatureAbbrev, Record, Blob); SignatureOffset = Stream.GetCurrentBitNo() - Blob.size() * 8; @@ -1639,6 +1679,18 @@ struct InputFileEntry { } // namespace +SourceLocation ASTWriter::getAffectingIncludeLoc(const SourceManager &SourceMgr, + const SrcMgr::FileInfo &File) { + SourceLocation IncludeLoc = File.getIncludeLoc(); + if (IncludeLoc.isValid()) { + FileID IncludeFID = SourceMgr.getFileID(IncludeLoc); + assert(IncludeFID.isValid() && "IncludeLoc in invalid file"); + if (!IsSLocAffecting[IncludeFID.ID]) + IncludeLoc = SourceLocation(); + } + return IncludeLoc; +} + void ASTWriter::WriteInputFiles(SourceManager &SourceMgr, HeaderSearchOptions &HSOpts) { using namespace llvm; @@ -1692,7 +1744,7 @@ void ASTWriter::WriteInputFiles(SourceManager &SourceMgr, Entry.IsSystemFile = isSystem(File.getFileCharacteristic()); Entry.IsTransient = Cache->IsTransient; Entry.BufferOverridden = Cache->BufferOverridden; - Entry.IsTopLevel = File.getIncludeLoc().isInvalid(); + Entry.IsTopLevel = getAffectingIncludeLoc(SourceMgr, File).isInvalid(); Entry.IsModuleMap = isModuleMap(File.getFileCharacteristic()); auto ContentHash = hash_code(-1); @@ -2219,7 +2271,7 @@ void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr, SLocEntryOffsets.push_back(Offset); // Starting offset of this entry within this module, so skip the dummy. Record.push_back(getAdjustedOffset(SLoc->getOffset()) - 2); - AddSourceLocation(File.getIncludeLoc(), Record); + AddSourceLocation(getAffectingIncludeLoc(SourceMgr, File), Record); Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding Record.push_back(File.hasLineDirectives()); @@ -3205,6 +3257,17 @@ void ASTWriter::WriteType(QualType T) { // Declaration Serialization //===----------------------------------------------------------------------===// +static bool IsInternalDeclFromFileContext(const Decl *D) { + auto *ND = dyn_cast(D); + if (!ND) + return false; + + if (!D->getDeclContext()->getRedeclContext()->isFileContext()) + return false; + + return ND->getFormalLinkage() == Linkage::Internal; +} + /// Write the block containing all of the declaration IDs /// lexically declared within the given DeclContext. /// @@ -3225,6 +3288,15 @@ uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context, if (DoneWritingDeclsAndTypes && !wasDeclEmitted(D)) continue; + // We don't need to write decls with internal linkage into reduced BMI. + // If such decls gets emitted due to it get used from inline functions, + // the program illegal. However, there are too many use of static inline + // functions in the global module fragment and it will be breaking change + // to forbid that. So we have to allow to emit such declarations from GMF. + if (GeneratingReducedBMI && !D->isFromExplicitGlobalModule() && + IsInternalDeclFromFileContext(D)) + continue; + KindDeclPairs.push_back(D->getKind()); KindDeclPairs.push_back(GetDeclRef(D).get()); } @@ -3886,6 +3958,13 @@ public: !Writer.wasDeclEmitted(DeclForLocalLookup)) continue; + // Try to avoid writing internal decls to reduced BMI. + // See comments in ASTWriter::WriteDeclContextLexicalBlock for details. + if (Writer.isGeneratingReducedBMI() && + !DeclForLocalLookup->isFromExplicitGlobalModule() && + IsInternalDeclFromFileContext(DeclForLocalLookup)) + continue; + DeclIDs.push_back(Writer.GetDeclRef(DeclForLocalLookup)); } return std::make_pair(Start, DeclIDs.size()); @@ -4257,6 +4336,12 @@ uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context, if (DoneWritingDeclsAndTypes && !wasDeclEmitted(ND)) continue; + // We don't need to force emitting internal decls into reduced BMI. + // See comments in ASTWriter::WriteDeclContextLexicalBlock for details. + if (GeneratingReducedBMI && !ND->isFromExplicitGlobalModule() && + IsInternalDeclFromFileContext(ND)) + continue; + GetDeclRef(ND); } } @@ -4917,8 +5002,7 @@ void ASTWriter::PrepareWritingSpecialDecls(Sema &SemaRef) { // is ill-formed. However, in practice, there are a lot of projects // uses `static inline` in the headers. So we can't get rid of all // static entities in reduced BMI now. - if (auto *ND = dyn_cast(D); - ND && ND->getFormalLinkage() == Linkage::Internal) + if (IsInternalDeclFromFileContext(D)) continue; } @@ -7645,6 +7729,12 @@ void ASTRecordWriter::writeOMPChildren(OMPChildren *Data) { AddStmt(Data->getChildren()[I]); } +void ASTRecordWriter::writeOpenACCVarList(const OpenACCClauseWithVarList *C) { + writeUInt32(C->getVarList().size()); + for (Expr *E : C->getVarList()) + AddStmt(E); +} + void ASTRecordWriter::writeOpenACCClause(const OpenACCClause *C) { writeEnum(C->getClauseKind()); writeSourceLocation(C->getBeginLoc()); @@ -7691,6 +7781,12 @@ void ASTRecordWriter::writeOpenACCClause(const OpenACCClause *C) { AddStmt(const_cast(NWC->getIntExpr())); return; } + case OpenACCClauseKind::Private: { + const auto *PC = cast(C); + writeSourceLocation(PC->getLParenLoc()); + writeOpenACCVarList(PC); + return; + } case OpenACCClauseKind::Finalize: case OpenACCClauseKind::IfPresent: case OpenACCClauseKind::Seq: @@ -7712,7 +7808,6 @@ void ASTRecordWriter::writeOpenACCClause(const OpenACCClause *C) { case OpenACCClauseKind::Link: case OpenACCClauseKind::NoCreate: case OpenACCClauseKind::Present: - case OpenACCClauseKind::Private: case OpenACCClauseKind::CopyOut: case OpenACCClauseKind::CopyIn: case OpenACCClauseKind::Create: diff --git a/clang/lib/Serialization/GeneratePCH.cpp b/clang/lib/Serialization/GeneratePCH.cpp index bed74399098d7f93ae4d1d43ab78ecb810fbf835..cc06106a47708ed7ea9828b694778f468db8141d 100644 --- a/clang/lib/Serialization/GeneratePCH.cpp +++ b/clang/lib/Serialization/GeneratePCH.cpp @@ -88,36 +88,34 @@ ASTDeserializationListener *PCHGenerator::GetASTDeserializationListener() { return &Writer; } -ReducedBMIGenerator::ReducedBMIGenerator(Preprocessor &PP, - InMemoryModuleCache &ModuleCache, - StringRef OutputFile) +void PCHGenerator::anchor() {} + +CXX20ModulesGenerator::CXX20ModulesGenerator(Preprocessor &PP, + InMemoryModuleCache &ModuleCache, + StringRef OutputFile, + bool GeneratingReducedBMI) : PCHGenerator( PP, ModuleCache, OutputFile, llvm::StringRef(), std::make_shared(), /*Extensions=*/ArrayRef>(), /*AllowASTWithErrors*/ false, /*IncludeTimestamps=*/false, /*BuildingImplicitModule=*/false, /*ShouldCacheASTInMemory=*/false, - /*GeneratingReducedBMI=*/true) {} + GeneratingReducedBMI) {} -Module *ReducedBMIGenerator::getEmittingModule(ASTContext &Ctx) { +Module *CXX20ModulesGenerator::getEmittingModule(ASTContext &Ctx) { Module *M = Ctx.getCurrentNamedModule(); assert(M && M->isNamedModuleUnit() && - "ReducedBMIGenerator should only be used with C++20 Named modules."); + "CXX20ModulesGenerator should only be used with C++20 Named modules."); return M; } -void ReducedBMIGenerator::HandleTranslationUnit(ASTContext &Ctx) { - // We need to do this to make sure the size of reduced BMI not to be larger - // than full BMI. - // +void CXX20ModulesGenerator::HandleTranslationUnit(ASTContext &Ctx) { // FIMXE: We'd better to wrap such options to a new class ASTWriterOptions // since this is not about searching header really. - // FIXME2: We'd better to move the class writing full BMI with reduced BMI. HeaderSearchOptions &HSOpts = getPreprocessor().getHeaderSearchInfo().getHeaderSearchOpts(); HSOpts.ModulesSkipDiagnosticOptions = true; HSOpts.ModulesSkipHeaderSearchPaths = true; - HSOpts.ModulesSkipPragmaDiagnosticMappings = true; PCHGenerator::HandleTranslationUnit(Ctx); @@ -135,3 +133,7 @@ void ReducedBMIGenerator::HandleTranslationUnit(ASTContext &Ctx) { *OS << getBufferPtr()->Data; OS->flush(); } + +void CXX20ModulesGenerator::anchor() {} + +void ReducedBMIGenerator::anchor() {} diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp index 287f6a52870056e63d099ae910c8ce9ee7cebe38..6901dbb415bf76fc65b9b980808c25d3640335b0 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp @@ -311,7 +311,7 @@ public: bool VisitUnaryOperator(const UnaryOperator *UO) { // Operator '*' and '!' are allowed as long as the operand is trivial. auto op = UO->getOpcode(); - if (op == UO_Deref || op == UO_AddrOf || op == UO_LNot) + if (op == UO_Deref || op == UO_AddrOf || op == UO_LNot || op == UO_Not) return Visit(UO->getSubExpr()); if (UO->isIncrementOp() || UO->isDecrementOp()) { @@ -331,6 +331,16 @@ public: return Visit(BO->getLHS()) && Visit(BO->getRHS()); } + bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { + // Compound assignment operator such as |= is trivial if its + // subexpresssions are trivial. + return VisitChildren(CAO); + } + + bool VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { + return VisitChildren(ASE); + } + bool VisitConditionalOperator(const ConditionalOperator *CO) { // Ternary operators are trivial if their conditions & values are trivial. return VisitChildren(CO); @@ -360,6 +370,16 @@ public: return TrivialFunctionAnalysis::isTrivialImpl(Callee, Cache); } + bool + VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) { + // Non-type template paramter is compile time constant and trivial. + return true; + } + + bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E) { + return VisitChildren(E); + } + bool VisitPredefinedExpr(const PredefinedExpr *E) { // A predefined identifier such as "func" is considered trivial. return true; @@ -463,6 +483,7 @@ public: bool VisitFixedPointLiteral(const FixedPointLiteral *E) { return true; } bool VisitCharacterLiteral(const CharacterLiteral *E) { return true; } bool VisitStringLiteral(const StringLiteral *E) { return true; } + bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { return true; } bool VisitConstantExpr(const ConstantExpr *CE) { // Constant expressions are trivial. diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h index 9ed8e7cab6abb9ed1484829899d926e7bb134239..ec1db1cc3358073d4d4d2dc6c14a97bb96edd600 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h @@ -50,6 +50,9 @@ std::optional isUncounted(const clang::CXXRecordDecl* Class); /// class, false if not, std::nullopt if inconclusive. std::optional isUncountedPtr(const clang::Type* T); +/// \returns true if Name is a RefPtr, Ref, or its variant, false if not. +bool isRefType(const std::string &Name); + /// \returns true if \p F creates ref-countable object from uncounted parameter, /// false if not. bool isCtorOfRefCounted(const clang::FunctionDecl *F); diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp index 8b41a949fd67345e6923b263bea6a20ef190c3ca..ae494de58da3da16b7babae11a25db9d938ecc5b 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp @@ -53,6 +53,13 @@ public: bool shouldVisitTemplateInstantiations() const { return true; } bool shouldVisitImplicitCode() const { return false; } + bool TraverseClassTemplateDecl(ClassTemplateDecl *Decl) { + if (isRefType(safeGetName(Decl))) + return true; + return RecursiveASTVisitor::TraverseClassTemplateDecl( + Decl); + } + bool VisitCallExpr(const CallExpr *CE) { Checker->visitCallExpr(CE); return true; diff --git a/clang/test/AST/HLSL/this-reference-template.hlsl b/clang/test/AST/HLSL/this-reference-template.hlsl index 60e057986ebf80fb5fec81fa80a276661c180b82..d427e73044b788f26df5fc8028f2d1bda2812e4f 100644 --- a/clang/test/AST/HLSL/this-reference-template.hlsl +++ b/clang/test/AST/HLSL/this-reference-template.hlsl @@ -24,7 +24,7 @@ void main() { // CHECK: -CXXMethodDecl 0x{{[0-9A-Fa-f]+}} line:8:5 getFirst 'K ()' implicit-inline // CHECK-NEXT:-CompoundStmt 0x{{[0-9A-Fa-f]+}} // CHECK-NEXT:-ReturnStmt 0x{{[0-9A-Fa-f]+}} -// CHECK-NEXT:-CXXDependentScopeMemberExpr 0x{{[0-9A-Fa-f]+}} '' lvalue .First +// CHECK-NEXT:-MemberExpr 0x{{[0-9A-Fa-f]+}} 'K' lvalue .First 0x{{[0-9A-Fa-f]+}} // CHECK-NEXT:-CXXThisExpr 0x{{[0-9A-Fa-f]+}} 'Pair' lvalue this // CHECK-NEXT:-CXXMethodDecl 0x{{[0-9A-Fa-f]+}} line:12:5 getSecond 'V ()' implicit-inline // CHECK-NEXT:-CompoundStmt 0x{{[0-9A-Fa-f]+}} diff --git a/clang/test/AST/Interp/c.c b/clang/test/AST/Interp/c.c index a5951158ed0e0d808303711ae1e69475fd006015..207da5fe812608497cc67088ac208597f92929bb 100644 --- a/clang/test/AST/Interp/c.c +++ b/clang/test/AST/Interp/c.c @@ -263,3 +263,10 @@ const int *p = &b; const __int128 K = (__int128)(int*)0; const unsigned __int128 KU = (unsigned __int128)(int*)0; #endif + + +int test3(void) { + int a[2]; + a[0] = test3; // all-error {{incompatible pointer to integer conversion assigning to 'int' from 'int (void)'}} + return 0; +} diff --git a/clang/test/AST/Interp/cxx23.cpp b/clang/test/AST/Interp/cxx23.cpp index 13cc9f43febc741706c6cb08740b043846b68db7..d1ec93e99803e558918f79e7645a6c651c73205a 100644 --- a/clang/test/AST/Interp/cxx23.cpp +++ b/clang/test/AST/Interp/cxx23.cpp @@ -157,3 +157,16 @@ namespace VirtualBases { D d; } } + +namespace LabelGoto { + constexpr int foo() { // all20-error {{never produces a constant expression}} + a: // all20-warning {{use of this statement in a constexpr function is a C++23 extension}} + goto a; // all20-note 2{{subexpression not valid in a constant expression}} \ + // ref23-note {{subexpression not valid in a constant expression}} \ + // expected23-note {{subexpression not valid in a constant expression}} + + return 1; + } + static_assert(foo() == 1, ""); // all-error {{not an integral constant expression}} \ + // all-note {{in call to}} +} diff --git a/clang/test/AST/Interp/functions.cpp b/clang/test/AST/Interp/functions.cpp index f9bb5d53634e0ba0cbcfe20d47a3f8ee0e33525b..a5bb9f1a19aaa7fe169cdfef09ee8506caa42a14 100644 --- a/clang/test/AST/Interp/functions.cpp +++ b/clang/test/AST/Interp/functions.cpp @@ -601,3 +601,19 @@ namespace FromIntegral { // both-warning {{variable length arrays}} #endif } + +namespace { + template using id = T; + template + constexpr void g() { + constexpr id f; + } + + static_assert((g(), true), ""); +} + +namespace { + /// The InitListExpr here is of void type. + void bir [[clang::annotate("B", {1, 2, 3, 4})]] (); // both-error {{'annotate' attribute requires parameter 1 to be a constant expression}} \ + // both-note {{subexpression not valid in a constant expression}} +} diff --git a/clang/test/AST/Interp/opencl.cl b/clang/test/AST/Interp/opencl.cl new file mode 100644 index 0000000000000000000000000000000000000000..fd7756fff7c11e807bf71ba1c36950b19f806c22 --- /dev/null +++ b/clang/test/AST/Interp/opencl.cl @@ -0,0 +1,38 @@ +// RUN: %clang_cc1 -fsyntax-only -cl-std=CL2.0 -verify=ref,both %s +// RUN: %clang_cc1 -fsyntax-only -cl-std=CL2.0 -verify=expected,both %s -fexperimental-new-constant-interpreter + +// both-no-diagnostics + +typedef int int2 __attribute__((ext_vector_type(2))); +typedef int int3 __attribute__((ext_vector_type(3))); +typedef int int4 __attribute__((ext_vector_type(4))); +typedef int int8 __attribute__((ext_vector_type(8))); +typedef int int16 __attribute__((ext_vector_type(16))); + +void foo(int3 arg1, int8 arg2) { + int4 auto1; + int16 *auto2; + int auto3; + int2 auto4; + struct S *incomplete1; + + int res1[vec_step(arg1) == 4 ? 1 : -1]; + int res2[vec_step(arg2) == 8 ? 1 : -1]; + int res3[vec_step(auto1) == 4 ? 1 : -1]; + int res4[vec_step(*auto2) == 16 ? 1 : -1]; + int res5[vec_step(auto3) == 1 ? 1 : -1]; + int res6[vec_step(auto4) == 2 ? 1 : -1]; + int res7[vec_step(int2) == 2 ? 1 : -1]; + int res8[vec_step(int3) == 4 ? 1 : -1]; + int res9[vec_step(int4) == 4 ? 1 : -1]; + int res10[vec_step(int8) == 8 ? 1 : -1]; + int res11[vec_step(int16) == 16 ? 1 : -1]; + int res12[vec_step(void) == 1 ? 1 : -1]; +} + +void negativeShift32(int a,int b) { + char array0[((int)1)<<40]; +} + +int2 A = {1,2}; +int4 B = {(int2)(1,2), (int2)(3,4)}; diff --git a/clang/test/AST/Interp/records.cpp b/clang/test/AST/Interp/records.cpp index 9307b9c090c5dd5dabf1e3955dfc3de309221927..771e5adfca34a45fcc60aeffbd9807176b6639b7 100644 --- a/clang/test/AST/Interp/records.cpp +++ b/clang/test/AST/Interp/records.cpp @@ -90,8 +90,7 @@ struct Ints2 { int a = 10; int b; }; -constexpr Ints2 ints22; // both-error {{without a user-provided default constructor}} \ - // expected-error {{must be initialized by a constant expression}} +constexpr Ints2 ints22; // both-error {{without a user-provided default constructor}} constexpr Ints2 I2 = Ints2{12, 25}; static_assert(I2.a == 12, ""); @@ -1031,6 +1030,12 @@ namespace ParenInit { // both-note {{required by 'constinit' specifier}} \ // both-note {{reference to temporary is not a constant expression}} \ // both-note {{temporary created here}} + + + /// Initializing an array. + constexpr void bar(int i, int j) { + int arr[4](i, j); + } } #endif @@ -1409,3 +1414,29 @@ namespace VirtualBases { static_assert((X*)(Y1*)&z != (X*)(Y2*)&z, ""); } } + +namespace ZeroInit { + struct S3 { + S3() = default; + S3(const S3&) = default; + S3(S3&&) = default; + constexpr S3(int n) : n(n) {} + int n; + }; + constexpr S3 s3d; // both-error {{default initialization of an object of const type 'const S3' without a user-provided default constructor}} + static_assert(s3d.n == 0, ""); +} + +namespace { +#if __cplusplus >= 202002L + struct C { + template constexpr C(const char (&)[N]) : n(N) {} + unsigned n; + }; + template + constexpr auto operator""_c() { return c.n; } + + constexpr auto waldo = "abc"_c; + static_assert(waldo == 4, ""); +#endif +} diff --git a/clang/test/AST/ast-dump-expr-json.cpp b/clang/test/AST/ast-dump-expr-json.cpp index bdd5ea19e418358210f901d3ea3c7ab85bd160f0..0fb07b0b434cc3861782e0119dae2d0d2e5dbade 100644 --- a/clang/test/AST/ast-dump-expr-json.cpp +++ b/clang/test/AST/ast-dump-expr-json.cpp @@ -2333,7 +2333,7 @@ void TestNonADLCall3() { // CHECK-NEXT: "kind": "FunctionDecl", // CHECK-NEXT: "name": "operator delete", // CHECK-NEXT: "type": { -// CHECK-NEXT: "qualType": "void (void *, unsigned long) noexcept" +// CHECK-NEXT: "qualType": "void (void *) noexcept" // CHECK-NEXT: } // CHECK-NEXT: }, // CHECK-NEXT: "inner": [ diff --git a/clang/test/AST/ast-dump-expr.cpp b/clang/test/AST/ast-dump-expr.cpp index de88f29bc4b0a99add10a6b43e2c616fab40394b..69e65e22d61d0d0d2198f360388f81db030ff94f 100644 --- a/clang/test/AST/ast-dump-expr.cpp +++ b/clang/test/AST/ast-dump-expr.cpp @@ -164,7 +164,7 @@ void UnaryExpressions(int *p) { // CHECK-NEXT: DeclRefExpr 0x{{[^ ]*}} 'int *' lvalue ParmVar 0x{{[^ ]*}} 'p' 'int *' ::delete p; - // CHECK: CXXDeleteExpr 0x{{[^ ]*}} 'void' global Function 0x{{[^ ]*}} 'operator delete' 'void (void *, unsigned long) noexcept' + // CHECK: CXXDeleteExpr 0x{{[^ ]*}} 'void' global Function 0x{{[^ ]*}} 'operator delete' 'void (void *) noexcept' // CHECK-NEXT: ImplicitCastExpr // CHECK-NEXT: DeclRefExpr 0x{{[^ ]*}} 'int *' lvalue ParmVar 0x{{[^ ]*}} 'p' 'int *' diff --git a/clang/test/AST/ast-dump-pragma-unroll.cpp b/clang/test/AST/ast-dump-pragma-unroll.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f9c254b803ff2b277ba11579e34659a99587c21d --- /dev/null +++ b/clang/test/AST/ast-dump-pragma-unroll.cpp @@ -0,0 +1,31 @@ +// RUN: %clang_cc1 -triple x86_64-unknown-unknown -ast-dump %s | FileCheck %s + +using size_t = unsigned long long; + +// CHECK: LoopHintAttr {{.*}} Implicit unroll UnrollCount Numeric +// CHECK: LoopHintAttr {{.*}} Implicit unroll UnrollCount Numeric +// CHECK: LoopHintAttr {{.*}} Implicit unroll Unroll Disable +// CHECK: LoopHintAttr {{.*}} Implicit unroll Unroll Disable +template +int value_dependent(int n) { + constexpr int N = 100; + auto init = [=]() { return Flag ? n : 0UL; }; + auto cond = [=](size_t ix) { return Flag ? ix != 0 : ix < 10; }; + auto iter = [=](size_t ix) { + return Flag ? ix & ~(1ULL << __builtin_clzll(ix)) : ix + 1; + }; + +#pragma unroll Flag ? 1 : N + for (size_t ix = init(); cond(ix); ix = iter(ix)) { + n *= n; + } +#pragma unroll Flag ? 0 : N + for (size_t ix = init(); cond(ix); ix = iter(ix)) { + n *= n; + } + return n; +} + +void test_value_dependent(int n) { + value_dependent(n); +} diff --git a/clang/test/AST/ast-dump-stmt-json.cpp b/clang/test/AST/ast-dump-stmt-json.cpp index a473d17da94244f842834dc2951589c717e7f22f..667a12a0120244e6a6adb7d20870df586a983233 100644 --- a/clang/test/AST/ast-dump-stmt-json.cpp +++ b/clang/test/AST/ast-dump-stmt-json.cpp @@ -994,7 +994,7 @@ void TestDependentGenericSelectionExpr(Ty T) { // CHECK-NEXT: "kind": "FunctionDecl", // CHECK-NEXT: "name": "operator delete", // CHECK-NEXT: "type": { -// CHECK-NEXT: "qualType": "void (void *, unsigned long) noexcept" +// CHECK-NEXT: "qualType": "void (void *) noexcept" // CHECK-NEXT: } // CHECK-NEXT: }, // CHECK-NEXT: "inner": [ @@ -1369,7 +1369,7 @@ void TestDependentGenericSelectionExpr(Ty T) { // CHECK-NEXT: "kind": "FunctionDecl", // CHECK-NEXT: "name": "operator delete", // CHECK-NEXT: "type": { -// CHECK-NEXT: "qualType": "void (void *, unsigned long) noexcept" +// CHECK-NEXT: "qualType": "void (void *) noexcept" // CHECK-NEXT: } // CHECK-NEXT: }, // CHECK-NEXT: "inner": [ @@ -1722,6 +1722,7 @@ void TestDependentGenericSelectionExpr(Ty T) { // CHECK-NEXT: "end": {} // CHECK-NEXT: }, // CHECK-NEXT: "isImplicit": true, +// CHECK-NEXT: "isUsed": true, // CHECK-NEXT: "name": "operator delete", // CHECK-NEXT: "mangledName": "_ZdlPv", // CHECK-NEXT: "type": { @@ -1809,126 +1810,6 @@ void TestDependentGenericSelectionExpr(Ty T) { // CHECK-NEXT: } -// CHECK-NOT: {{^}}Dumping -// CHECK: "kind": "FunctionDecl", -// CHECK-NEXT: "loc": {}, -// CHECK-NEXT: "range": { -// CHECK-NEXT: "begin": {}, -// CHECK-NEXT: "end": {} -// CHECK-NEXT: }, -// CHECK-NEXT: "isImplicit": true, -// CHECK-NEXT: "isUsed": true, -// CHECK-NEXT: "name": "operator delete", -// CHECK-NEXT: "mangledName": "_ZdlPvm", -// CHECK-NEXT: "type": { -// CHECK-NEXT: "qualType": "void (void *, unsigned long) noexcept" -// CHECK-NEXT: }, -// CHECK-NEXT: "inner": [ -// CHECK-NEXT: { -// CHECK-NEXT: "id": "0x{{.*}}", -// CHECK-NEXT: "kind": "ParmVarDecl", -// CHECK-NEXT: "loc": {}, -// CHECK-NEXT: "range": { -// CHECK-NEXT: "begin": {}, -// CHECK-NEXT: "end": {} -// CHECK-NEXT: }, -// CHECK-NEXT: "isImplicit": true, -// CHECK-NEXT: "type": { -// CHECK-NEXT: "qualType": "void *" -// CHECK-NEXT: } -// CHECK-NEXT: }, -// CHECK-NEXT: { -// CHECK-NEXT: "id": "0x{{.*}}", -// CHECK-NEXT: "kind": "ParmVarDecl", -// CHECK-NEXT: "loc": {}, -// CHECK-NEXT: "range": { -// CHECK-NEXT: "begin": {}, -// CHECK-NEXT: "end": {} -// CHECK-NEXT: }, -// CHECK-NEXT: "isImplicit": true, -// CHECK-NEXT: "type": { -// CHECK-NEXT: "qualType": "unsigned long" -// CHECK-NEXT: } -// CHECK-NEXT: }, -// CHECK-NEXT: { -// CHECK-NEXT: "id": "0x{{.*}}", -// CHECK-NEXT: "kind": "VisibilityAttr", -// CHECK-NEXT: "range": { -// CHECK-NEXT: "begin": {}, -// CHECK-NEXT: "end": {} -// CHECK-NEXT: }, -// CHECK-NEXT: "implicit": true, -// CHECK-NEXT: "visibility": "default" -// CHECK-NEXT: } -// CHECK-NEXT: ] -// CHECK-NEXT: } - -// CHECK-NOT: {{^}}Dumping -// CHECK: "kind": "FunctionDecl", -// CHECK-NEXT: "loc": {}, -// CHECK-NEXT: "range": { -// CHECK-NEXT: "begin": {}, -// CHECK-NEXT: "end": {} -// CHECK-NEXT: }, -// CHECK-NEXT: "isImplicit": true, -// CHECK-NEXT: "name": "operator delete", -// CHECK-NEXT: "mangledName": "_ZdlPvmSt11align_val_t", -// CHECK-NEXT: "type": { -// CHECK-NEXT: "qualType": "void (void *, unsigned long, std::align_val_t) noexcept" -// CHECK-NEXT: }, -// CHECK-NEXT: "inner": [ -// CHECK-NEXT: { -// CHECK-NEXT: "id": "0x{{.*}}", -// CHECK-NEXT: "kind": "ParmVarDecl", -// CHECK-NEXT: "loc": {}, -// CHECK-NEXT: "range": { -// CHECK-NEXT: "begin": {}, -// CHECK-NEXT: "end": {} -// CHECK-NEXT: }, -// CHECK-NEXT: "isImplicit": true, -// CHECK-NEXT: "type": { -// CHECK-NEXT: "qualType": "void *" -// CHECK-NEXT: } -// CHECK-NEXT: }, -// CHECK-NEXT: { -// CHECK-NEXT: "id": "0x{{.*}}", -// CHECK-NEXT: "kind": "ParmVarDecl", -// CHECK-NEXT: "loc": {}, -// CHECK-NEXT: "range": { -// CHECK-NEXT: "begin": {}, -// CHECK-NEXT: "end": {} -// CHECK-NEXT: }, -// CHECK-NEXT: "isImplicit": true, -// CHECK-NEXT: "type": { -// CHECK-NEXT: "qualType": "unsigned long" -// CHECK-NEXT: } -// CHECK-NEXT: }, -// CHECK-NEXT: { -// CHECK-NEXT: "id": "0x{{.*}}", -// CHECK-NEXT: "kind": "ParmVarDecl", -// CHECK-NEXT: "loc": {}, -// CHECK-NEXT: "range": { -// CHECK-NEXT: "begin": {}, -// CHECK-NEXT: "end": {} -// CHECK-NEXT: }, -// CHECK-NEXT: "isImplicit": true, -// CHECK-NEXT: "type": { -// CHECK-NEXT: "qualType": "std::align_val_t" -// CHECK-NEXT: } -// CHECK-NEXT: }, -// CHECK-NEXT: { -// CHECK-NEXT: "id": "0x{{.*}}", -// CHECK-NEXT: "kind": "VisibilityAttr", -// CHECK-NEXT: "range": { -// CHECK-NEXT: "begin": {}, -// CHECK-NEXT: "end": {} -// CHECK-NEXT: }, -// CHECK-NEXT: "implicit": true, -// CHECK-NEXT: "visibility": "default" -// CHECK-NEXT: } -// CHECK-NEXT: ] -// CHECK-NEXT: } - // CHECK-NOT: {{^}}Dumping // CHECK: "kind": "FunctionDecl", // CHECK-NEXT: "loc": {}, @@ -2025,125 +1906,6 @@ void TestDependentGenericSelectionExpr(Ty T) { // CHECK-NEXT: } -// CHECK-NOT: {{^}}Dumping -// CHECK: "kind": "FunctionDecl", -// CHECK-NEXT: "loc": {}, -// CHECK-NEXT: "range": { -// CHECK-NEXT: "begin": {}, -// CHECK-NEXT: "end": {} -// CHECK-NEXT: }, -// CHECK-NEXT: "isImplicit": true, -// CHECK-NEXT: "name": "operator delete[]", -// CHECK-NEXT: "mangledName": "_ZdaPvm", -// CHECK-NEXT: "type": { -// CHECK-NEXT: "qualType": "void (void *, unsigned long) noexcept" -// CHECK-NEXT: }, -// CHECK-NEXT: "inner": [ -// CHECK-NEXT: { -// CHECK-NEXT: "id": "0x{{.*}}", -// CHECK-NEXT: "kind": "ParmVarDecl", -// CHECK-NEXT: "loc": {}, -// CHECK-NEXT: "range": { -// CHECK-NEXT: "begin": {}, -// CHECK-NEXT: "end": {} -// CHECK-NEXT: }, -// CHECK-NEXT: "isImplicit": true, -// CHECK-NEXT: "type": { -// CHECK-NEXT: "qualType": "void *" -// CHECK-NEXT: } -// CHECK-NEXT: }, -// CHECK-NEXT: { -// CHECK-NEXT: "id": "0x{{.*}}", -// CHECK-NEXT: "kind": "ParmVarDecl", -// CHECK-NEXT: "loc": {}, -// CHECK-NEXT: "range": { -// CHECK-NEXT: "begin": {}, -// CHECK-NEXT: "end": {} -// CHECK-NEXT: }, -// CHECK-NEXT: "isImplicit": true, -// CHECK-NEXT: "type": { -// CHECK-NEXT: "qualType": "unsigned long" -// CHECK-NEXT: } -// CHECK-NEXT: }, -// CHECK-NEXT: { -// CHECK-NEXT: "id": "0x{{.*}}", -// CHECK-NEXT: "kind": "VisibilityAttr", -// CHECK-NEXT: "range": { -// CHECK-NEXT: "begin": {}, -// CHECK-NEXT: "end": {} -// CHECK-NEXT: }, -// CHECK-NEXT: "implicit": true, -// CHECK-NEXT: "visibility": "default" -// CHECK-NEXT: } -// CHECK-NEXT: ] -// CHECK-NEXT: } - -// CHECK-NOT: {{^}}Dumping -// CHECK: "kind": "FunctionDecl", -// CHECK-NEXT: "loc": {}, -// CHECK-NEXT: "range": { -// CHECK-NEXT: "begin": {}, -// CHECK-NEXT: "end": {} -// CHECK-NEXT: }, -// CHECK-NEXT: "isImplicit": true, -// CHECK-NEXT: "name": "operator delete[]", -// CHECK-NEXT: "mangledName": "_ZdaPvmSt11align_val_t", -// CHECK-NEXT: "type": { -// CHECK-NEXT: "qualType": "void (void *, unsigned long, std::align_val_t) noexcept" -// CHECK-NEXT: }, -// CHECK-NEXT: "inner": [ -// CHECK-NEXT: { -// CHECK-NEXT: "id": "0x{{.*}}", -// CHECK-NEXT: "kind": "ParmVarDecl", -// CHECK-NEXT: "loc": {}, -// CHECK-NEXT: "range": { -// CHECK-NEXT: "begin": {}, -// CHECK-NEXT: "end": {} -// CHECK-NEXT: }, -// CHECK-NEXT: "isImplicit": true, -// CHECK-NEXT: "type": { -// CHECK-NEXT: "qualType": "void *" -// CHECK-NEXT: } -// CHECK-NEXT: }, -// CHECK-NEXT: { -// CHECK-NEXT: "id": "0x{{.*}}", -// CHECK-NEXT: "kind": "ParmVarDecl", -// CHECK-NEXT: "loc": {}, -// CHECK-NEXT: "range": { -// CHECK-NEXT: "begin": {}, -// CHECK-NEXT: "end": {} -// CHECK-NEXT: }, -// CHECK-NEXT: "isImplicit": true, -// CHECK-NEXT: "type": { -// CHECK-NEXT: "qualType": "unsigned long" -// CHECK-NEXT: } -// CHECK-NEXT: }, -// CHECK-NEXT: { -// CHECK-NEXT: "id": "0x{{.*}}", -// CHECK-NEXT: "kind": "ParmVarDecl", -// CHECK-NEXT: "loc": {}, -// CHECK-NEXT: "range": { -// CHECK-NEXT: "begin": {}, -// CHECK-NEXT: "end": {} -// CHECK-NEXT: }, -// CHECK-NEXT: "isImplicit": true, -// CHECK-NEXT: "type": { -// CHECK-NEXT: "qualType": "std::align_val_t" -// CHECK-NEXT: } -// CHECK-NEXT: }, -// CHECK-NEXT: { -// CHECK-NEXT: "id": "0x{{.*}}", -// CHECK-NEXT: "kind": "VisibilityAttr", -// CHECK-NEXT: "range": { -// CHECK-NEXT: "begin": {}, -// CHECK-NEXT: "end": {} -// CHECK-NEXT: }, -// CHECK-NEXT: "implicit": true, -// CHECK-NEXT: "visibility": "default" -// CHECK-NEXT: } -// CHECK-NEXT: ] -// CHECK-NEXT: } - // CHECK-NOT: {{^}}Dumping // CHECK: "kind": "FunctionTemplateDecl", // CHECK-NEXT: "loc": { diff --git a/clang/test/AST/ast-dump-template-json-win32-mangler-crash.cpp b/clang/test/AST/ast-dump-template-json-win32-mangler-crash.cpp index cf740516db6f4b4e7d5b8459b7c8327835bc4d4c..5ac55d269dce48507b9805e8e1345fedc8b5c6d1 100644 --- a/clang/test/AST/ast-dump-template-json-win32-mangler-crash.cpp +++ b/clang/test/AST/ast-dump-template-json-win32-mangler-crash.cpp @@ -1846,6 +1846,42 @@ int main() // CHECK-NEXT: "kind": "VarTemplateDecl", // CHECK-NEXT: "name": "is_const_v" // CHECK-NEXT: } +// CHECK-NEXT: ], +// CHECK-NEXT: "inner": [ +// CHECK-NEXT: { +// CHECK-NEXT: "kind": "TemplateArgument", +// CHECK-NEXT: "type": { +// CHECK-NEXT: "qualType": "const _Ty" +// CHECK-NEXT: }, +// CHECK-NEXT: "inner": [ +// CHECK-NEXT: { +// CHECK-NEXT: "id": "0x{{.*}}", +// CHECK-NEXT: "kind": "QualType", +// CHECK-NEXT: "type": { +// CHECK-NEXT: "qualType": "const _Ty" +// CHECK-NEXT: }, +// CHECK-NEXT: "qualifiers": "const", +// CHECK-NEXT: "inner": [ +// CHECK-NEXT: { +// CHECK-NEXT: "id": "0x{{.*}}", +// CHECK-NEXT: "kind": "TemplateTypeParmType", +// CHECK-NEXT: "type": { +// CHECK-NEXT: "qualType": "_Ty" +// CHECK-NEXT: }, +// CHECK-NEXT: "isDependent": true, +// CHECK-NEXT: "isInstantiationDependent": true, +// CHECK-NEXT: "depth": 0, +// CHECK-NEXT: "index": 0, +// CHECK-NEXT: "decl": { +// CHECK-NEXT: "id": "0x{{.*}}", +// CHECK-NEXT: "kind": "TemplateTypeParmDecl", +// CHECK-NEXT: "name": "_Ty" +// CHECK-NEXT: } +// CHECK-NEXT: } +// CHECK-NEXT: ] +// CHECK-NEXT: } +// CHECK-NEXT: ] +// CHECK-NEXT: } // CHECK-NEXT: ] // CHECK-NEXT: } // CHECK-NEXT: ] @@ -1900,6 +1936,32 @@ int main() // CHECK-NEXT: "kind": "VarTemplateDecl", // CHECK-NEXT: "name": "is_reference_v" // CHECK-NEXT: } +// CHECK-NEXT: ], +// CHECK-NEXT: "inner": [ +// CHECK-NEXT: { +// CHECK-NEXT: "kind": "TemplateArgument", +// CHECK-NEXT: "type": { +// CHECK-NEXT: "qualType": "_Ty" +// CHECK-NEXT: }, +// CHECK-NEXT: "inner": [ +// CHECK-NEXT: { +// CHECK-NEXT: "id": "0x{{.*}}", +// CHECK-NEXT: "kind": "TemplateTypeParmType", +// CHECK-NEXT: "type": { +// CHECK-NEXT: "qualType": "_Ty" +// CHECK-NEXT: }, +// CHECK-NEXT: "isDependent": true, +// CHECK-NEXT: "isInstantiationDependent": true, +// CHECK-NEXT: "depth": 0, +// CHECK-NEXT: "index": 0, +// CHECK-NEXT: "decl": { +// CHECK-NEXT: "id": "0x{{.*}}", +// CHECK-NEXT: "kind": "TemplateTypeParmDecl", +// CHECK-NEXT: "name": "_Ty" +// CHECK-NEXT: } +// CHECK-NEXT: } +// CHECK-NEXT: ] +// CHECK-NEXT: } // CHECK-NEXT: ] // CHECK-NEXT: } // CHECK-NEXT: ] @@ -2565,6 +2627,32 @@ int main() // CHECK-NEXT: "kind": "VarTemplateDecl", // CHECK-NEXT: "name": "is_function_v" // CHECK-NEXT: } +// CHECK-NEXT: ], +// CHECK-NEXT: "inner": [ +// CHECK-NEXT: { +// CHECK-NEXT: "kind": "TemplateArgument", +// CHECK-NEXT: "type": { +// CHECK-NEXT: "qualType": "_Ty1" +// CHECK-NEXT: }, +// CHECK-NEXT: "inner": [ +// CHECK-NEXT: { +// CHECK-NEXT: "id": "0x{{.*}}", +// CHECK-NEXT: "kind": "TemplateTypeParmType", +// CHECK-NEXT: "type": { +// CHECK-NEXT: "qualType": "_Ty1" +// CHECK-NEXT: }, +// CHECK-NEXT: "isDependent": true, +// CHECK-NEXT: "isInstantiationDependent": true, +// CHECK-NEXT: "depth": 0, +// CHECK-NEXT: "index": 0, +// CHECK-NEXT: "decl": { +// CHECK-NEXT: "id": "0x{{.*}}", +// CHECK-NEXT: "kind": "TemplateTypeParmDecl", +// CHECK-NEXT: "name": "_Ty1" +// CHECK-NEXT: } +// CHECK-NEXT: } +// CHECK-NEXT: ] +// CHECK-NEXT: } // CHECK-NEXT: ] // CHECK-NEXT: } // CHECK-NEXT: ] diff --git a/clang/test/AST/ast-dump-templates.cpp b/clang/test/AST/ast-dump-templates.cpp index d25ef36dd4d32c001d54d071484cdfea2ec95181..9fcafbcbcc46b69f0acce5affb17513d164d7735 100644 --- a/clang/test/AST/ast-dump-templates.cpp +++ b/clang/test/AST/ast-dump-templates.cpp @@ -104,3 +104,17 @@ void (*q)() = f<>; // CHECK1: template<> void f<0L>() // CHECK1: template<> void f<0U>() } + +namespace test6 { +template +constexpr bool C = true; + +template +void func() { + C; +// DUMP: UnresolvedLookupExpr {{.*}} '' lvalue (no ADL) = 'C' +// DUMP-NEXT: `-TemplateArgument type 'Key' +// DUMP-NEXT: `-TemplateTypeParmType {{.*}} 'Key' dependent depth 0 index 0 +// DUMP-NEXT: `-TemplateTypeParm {{.*}} 'Key' +} +} diff --git a/clang/test/AST/ast-print-openacc-compute-construct.cpp b/clang/test/AST/ast-print-openacc-compute-construct.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cd39ea087b3cadef4a40db73c95962cfe5057e0c --- /dev/null +++ b/clang/test/AST/ast-print-openacc-compute-construct.cpp @@ -0,0 +1,42 @@ +// RUN: %clang_cc1 -fopenacc -ast-print %s -o - | FileCheck %s + +void foo() { + int i; + float array[5]; +// CHECK: #pragma acc parallel default(none) +// CHECK-NEXT: while (true) +#pragma acc parallel default(none) + while(true); +// CHECK: #pragma acc serial default(present) +// CHECK-NEXT: while (true) +#pragma acc serial default(present) + while(true); +// CHECK: #pragma acc kernels if(i == array[1]) +// CHECK-NEXT: while (true) +#pragma acc kernels if(i == array[1]) + while(true); +// CHECK: #pragma acc parallel self(i == 3) +// CHECK-NEXT: while (true) +#pragma acc parallel self(i == 3) + while(true); + +// CHECK: #pragma acc parallel num_gangs(i, (int)array[2]) +// CHECK-NEXT: while (true) +#pragma acc parallel num_gangs(i, (int)array[2]) + while(true); + +// CHECK: #pragma acc parallel num_workers(i) +// CHECK-NEXT: while (true) +#pragma acc parallel num_workers(i) + while(true); + +// CHECK: #pragma acc parallel vector_length((int)array[1]) +// CHECK-NEXT: while (true) +#pragma acc parallel vector_length((int)array[1]) + while(true); + +// CHECK: #pragma acc parallel private(i, array[1], array, array[1:2]) +#pragma acc parallel private(i, array[1], array, array[1:2]) + while(true); +} + diff --git a/clang/test/Analysis/Checkers/WebKit/call-args-regression-traverse-decl-crash.cpp b/clang/test/Analysis/Checkers/WebKit/call-args-regression-traverse-decl-crash.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3d8e822025f62b2074d74409eb917e4779757926 --- /dev/null +++ b/clang/test/Analysis/Checkers/WebKit/call-args-regression-traverse-decl-crash.cpp @@ -0,0 +1,7 @@ +// RUN: %clang_analyze_cc1 -analyzer-checker=alpha.webkit.UncountedCallArgsChecker -verify %s +// expected-no-diagnostics + +template struct T; +template