Skip to content

Commit 5c40d7f

Browse files
AmrDeveloperlanza
authored andcommitted
[CIR] Backport UnaryExtension for AggregateExpr (#1948)
Backporting UnaryExtension for AggregateExpr from the upstream
1 parent fff4a69 commit 5c40d7f

File tree

20 files changed

+252
-27
lines changed

20 files changed

+252
-27
lines changed

clang/include/clang/Basic/LangOptions.def

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -400,6 +400,7 @@ LANGOPT(APINotesModules, 1, 0, NotCompatible, "use module-based external API not
400400
LANGOPT(SwiftVersionIndependentAPINotes, 1, 0, NotCompatible, "use external API notes capturing all versions")
401401

402402
LANGOPT(CIRWarnings, 1, 0, NotCompatible, "emit warnings with ClangIR")
403+
LANGOPT(EmitCIRToFile, 1, 0, NotCompatible, "emit Clang IR to disk")
403404

404405
LANGOPT(SanitizeAddressFieldPadding, 2, 0, NotCompatible, "controls how aggressive is ASan "
405406
"field padding (0: none, 1:least "

clang/include/clang/Driver/Options.td

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2933,6 +2933,7 @@ defm gnu89_inline : BoolFOption<"gnu89-inline",
29332933
"Use the gnu89 inline semantics">,
29342934
NegFlag<SetFalse>>, ShouldParseIf<!strconcat("!", cplusplus.KeyPath)>;
29352935
def fgnu_runtime : Flag<["-"], "fgnu-runtime">, Group<f_Group>,
2936+
Visibility<[ClangOption, CC1Option]>,
29362937
HelpText<"Generate output compatible with the standard GNU Objective-C runtime">;
29372938
// This used to be a standalone flag but is now mapped to
29382939
// -Wno-error=invalid-gnu-asm-cast, which is the only thing the flag used to
@@ -3155,13 +3156,16 @@ defm clangir : BoolFOption<"clangir",
31553156
PosFlag<SetTrue, [], [ClangOption, CC1Option], "Use the ClangIR pipeline to compile">,
31563157
NegFlag<SetFalse, [], [ClangOption, CC1Option], "Use the AST -> LLVM pipeline to compile">,
31573158
BothFlags<[], [ClangOption, CC1Option], "">>;
3158-
def fcir_output_EQ : Joined<["-"], "fcir-output=">,
3159+
def fcir_output_EQ : Joined<["-"], "fcir-output=">, Group<f_Group>,
31593160
Visibility<[ClangOption, CC1Option]>,
3161+
Flags<[NoArgumentUnused]>,
31603162
HelpText<"Write Clang IR output to <file>">,
31613163
MarshallingInfoString<LangOpts<"CIRFile">>;
3162-
def fcir_output : Flag<["-"], "fcir-output">,
3164+
def fcir_output : Flag<["-"], "fcir-output">, Group<f_Group>,
31633165
Visibility<[ClangOption, CC1Option]>,
3164-
HelpText<"Write Clang IR output to <input>.cir">;
3166+
Flags<[NoArgumentUnused]>,
3167+
HelpText<"Write Clang IR output to <input>.cir">,
3168+
MarshallingInfoFlag<LangOpts<"EmitCIRToFile">>;
31653169
defm cir_warnings : BoolFOption<"cir-warnings",
31663170
LangOpts<"CIRWarnings">, DefaultFalse,
31673171
PosFlag<SetTrue, [], [ClangOption, CC1Option], "Use">,

clang/include/clang/Frontend/CompilerInstance.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
#include "llvm/ADT/ArrayRef.h"
2323
#include "llvm/ADT/DenseMap.h"
2424
#include "llvm/ADT/IntrusiveRefCntPtr.h"
25+
#include "llvm/ADT/SmallVector.h"
2526
#include "llvm/ADT/StringRef.h"
2627
#include "llvm/Support/BuryPointer.h"
2728
#include "llvm/Support/FileSystem.h"
@@ -193,6 +194,11 @@ class CompilerInstance : public ModuleLoader {
193194
/// Force an output buffer.
194195
std::unique_ptr<llvm::raw_pwrite_stream> OutputStream;
195196

197+
/// Diagnostics about VFS overlays that should be emitted after executing
198+
/// the frontend action.
199+
llvm::SmallVector<std::pair<diag::kind, std::string>, 4>
200+
PendingVFSDiagnostics;
201+
196202
CompilerInstance(const CompilerInstance &) = delete;
197203
void operator=(const CompilerInstance &) = delete;
198204
public:

clang/include/clang/Frontend/CompilerInvocation.h

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -391,12 +391,16 @@ createVFSFromCompilerInvocation(const CompilerInvocation &CI,
391391

392392
IntrusiveRefCntPtr<llvm::vfs::FileSystem> createVFSFromCompilerInvocation(
393393
const CompilerInvocation &CI, DiagnosticsEngine &Diags,
394-
IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS);
394+
IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS,
395+
llvm::SmallVectorImpl<std::pair<diag::kind, std::string>> *DelayedDiags =
396+
nullptr);
395397

396398
IntrusiveRefCntPtr<llvm::vfs::FileSystem>
397399
createVFSFromOverlayFiles(ArrayRef<std::string> VFSOverlayFiles,
398400
DiagnosticsEngine &Diags,
399-
IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS);
401+
IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS,
402+
llvm::SmallVectorImpl<std::pair<diag::kind, std::string>>
403+
*DelayedDiags = nullptr);
400404

401405
} // namespace clang
402406

clang/include/clang/Frontend/FrontendOptions.h

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -443,6 +443,8 @@ class FrontendOptions {
443443
// Enable Clang IR analysis only pipeline that uses traditional codegen
444444
// pipeline.
445445
unsigned ClangIRAnalysisOnly : 1;
446+
// Emit Clang IR to a side file.
447+
unsigned EmitClangIRFile : 1;
446448
CodeCompleteOptions CodeCompleteOpts;
447449

448450
/// Specifies the output format of the AST.
@@ -451,6 +453,7 @@ class FrontendOptions {
451453
std::string ClangIRLifetimeCheckOpts;
452454
std::string ClangIRIdiomRecognizerOpts;
453455
std::string ClangIRLibOptOpts;
456+
std::string ClangIRFile;
454457

455458
frontend::MLIRDialectKind MLIRTargetDialect = frontend::MLIR_CORE;
456459

@@ -581,9 +584,10 @@ class FrontendOptions {
581584
EmitPrettySymbolGraphs(false), GenReducedBMI(false),
582585
UseClangIRPipeline(false), ClangIRDirectLowering(false),
583586
ClangIRDisablePasses(false), ClangIRDisableCIRVerifier(false),
584-
ClangIRLifetimeCheck(false), ClangIRIdiomRecognizer(false),
585-
ClangIRLibOpt(false), ClangIRCallConvLowering(true),
586-
ClangIREnableMem2Reg(false), ClangIRAnalysisOnly(false),
587+
ClangIRVerifyDiags(false), ClangIRLifetimeCheck(false),
588+
ClangIRIdiomRecognizer(false), ClangIRLibOpt(false),
589+
ClangIRCallConvLowering(true), ClangIREnableMem2Reg(false),
590+
ClangIRAnalysisOnly(false), EmitClangIRFile(false),
587591
TimeTraceGranularity(500), TimeTraceVerbose(false) {}
588592

589593
/// getInputKindForExtension - Return the appropriate input kind for a file

clang/lib/CIR/CodeGen/CIRGenExpr.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2042,7 +2042,8 @@ LValue CIRGenFunction::emitCastLValue(const CastExpr *E) {
20422042
assert(0 && "NYI");
20432043
case CK_BaseToDerived: {
20442044
const auto *derivedClassTy = E->getType()->castAs<RecordType>();
2045-
auto *derivedClassDecl = cast<CXXRecordDecl>(derivedClassTy->getDecl());
2045+
auto *derivedClassDecl =
2046+
cast<CXXRecordDecl>(derivedClassTy->getOriginalDecl());
20462047

20472048
LValue lv = emitLValue(E->getSubExpr());
20482049

clang/lib/CIR/CodeGen/CIRGenExprAgg.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
186186
}
187187
void VisitCoyieldExpr(CoyieldExpr *E) { llvm_unreachable("NYI"); }
188188
void VisitUnaryCoawait(UnaryOperator *E) { llvm_unreachable("NYI"); }
189-
void VisitUnaryExtension(UnaryOperator *E) { llvm_unreachable("NYI"); }
189+
void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
190190
void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
191191
llvm_unreachable("NYI");
192192
}

clang/lib/CIR/FrontendAction/CIRGenAction.cpp

Lines changed: 52 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,9 +47,11 @@
4747
#include "llvm/LTO/LTOBackend.h"
4848
#include "llvm/Linker/Linker.h"
4949
#include "llvm/Pass.h"
50+
#include "llvm/ADT/SmallString.h"
5051
#include "llvm/Support/MemoryBuffer.h"
5152
#include "llvm/Support/Signals.h"
5253
#include "llvm/Support/SourceMgr.h"
54+
#include "llvm/Support/Path.h"
5355
#include "llvm/Support/TimeProfiler.h"
5456
#include "llvm/Support/Timer.h"
5557
#include "llvm/Support/ToolOutputFile.h"
@@ -118,6 +120,7 @@ class CIRGenConsumer : public clang::ASTConsumer {
118120
[[maybe_unused]] const LangOptions &langOptions;
119121
const FrontendOptions &feOptions;
120122

123+
std::string InputFileName;
121124
std::unique_ptr<raw_pwrite_stream> outputStream;
122125

123126
ASTContext *astContext{nullptr};
@@ -133,13 +136,14 @@ class CIRGenConsumer : public clang::ASTConsumer {
133136
CodeGenOptions &codeGenOptions,
134137
const TargetOptions &targetOptions,
135138
const LangOptions &langOptions,
136-
const FrontendOptions &feOptions,
139+
const FrontendOptions &feOptions, StringRef InputFile,
137140
std::unique_ptr<raw_pwrite_stream> os)
138141
: action(action), compilerInstance(compilerInstance),
139142
diagnosticsEngine(diagnosticsEngine),
140143
headerSearchOptions(headerSearchOptions),
141144
codeGenOptions(codeGenOptions), targetOptions(targetOptions),
142145
langOptions(langOptions), feOptions(feOptions),
146+
InputFileName(InputFile.str()),
143147
outputStream(std::move(os)), FS(VFS),
144148
gen(std::make_unique<CIRGenerator>(diagnosticsEngine, std::move(VFS),
145149
codeGenOptions)) {}
@@ -265,6 +269,50 @@ class CIRGenConsumer : public clang::ASTConsumer {
265269
}
266270
}
267271

272+
bool EmitCIR = langOptions.EmitCIRToFile || feOptions.EmitClangIRFile ||
273+
!langOptions.CIRFile.empty() ||
274+
!feOptions.ClangIRFile.empty();
275+
if (EmitCIR) {
276+
std::unique_ptr<raw_pwrite_stream> CIRStream;
277+
llvm::SmallString<128> DefaultPath;
278+
if (!feOptions.ClangIRFile.empty()) {
279+
CIRStream = compilerInstance.createOutputFile(
280+
feOptions.ClangIRFile,
281+
/*Binary=*/false,
282+
/*RemoveFileOnSignal=*/true,
283+
/*UseTemporary=*/true);
284+
} else if (!langOptions.CIRFile.empty()) {
285+
CIRStream = compilerInstance.createOutputFile(
286+
langOptions.CIRFile,
287+
/*Binary=*/false,
288+
/*RemoveFileOnSignal=*/true,
289+
/*UseTemporary=*/true);
290+
} else {
291+
if (!feOptions.OutputFile.empty() && feOptions.OutputFile != "-") {
292+
DefaultPath = feOptions.OutputFile;
293+
} else if (!InputFileName.empty() && InputFileName != "-") {
294+
DefaultPath = InputFileName;
295+
} else if (!feOptions.Inputs.empty() && feOptions.Inputs[0].isFile() &&
296+
feOptions.Inputs[0].getFile() != "-") {
297+
DefaultPath = feOptions.Inputs[0].getFile();
298+
} else {
299+
DefaultPath = "clangir-output";
300+
}
301+
llvm::sys::path::replace_extension(DefaultPath, "cir");
302+
CIRStream = compilerInstance.createOutputFile(
303+
DefaultPath,
304+
/*Binary=*/false,
305+
/*RemoveFileOnSignal=*/true,
306+
/*UseTemporary=*/true);
307+
}
308+
309+
if (CIRStream) {
310+
mlir::OpPrintingFlags Flags;
311+
Flags.enableDebugInfo(/*enable=*/true, /*prettyForm=*/false);
312+
mlirMod->print(*CIRStream, Flags);
313+
}
314+
}
315+
268316
auto emitMLIR = [&](mlir::Operation *mlirMod, bool verify) {
269317
assert(mlirMod &&
270318
"MLIR module does not exist, but lowering did not fail?");
@@ -399,7 +447,7 @@ CIRGenAction::CreateASTConsumer(CompilerInstance &ci, StringRef inputFile) {
399447
auto Result = std::make_unique<cir::CIRGenConsumer>(
400448
action, ci, ci.getDiagnostics(), &ci.getVirtualFileSystem(),
401449
ci.getHeaderSearchOpts(), ci.getCodeGenOpts(), ci.getTargetOpts(),
402-
ci.getLangOpts(), ci.getFrontendOpts(), std::move(out));
450+
ci.getLangOpts(), ci.getFrontendOpts(), inputFile, std::move(out));
403451
cgConsumer = Result.get();
404452

405453
// Enable generating macro debug info only when debug info is not disabled and
@@ -507,7 +555,8 @@ AnalysisOnlyActionBase::CreateASTConsumer(clang::CompilerInstance &ci,
507555
Consumers.push_back(std::make_unique<cir::CIRGenConsumer>(
508556
CIRGenAction::OutputType::None, ci, ci.getDiagnostics(),
509557
&ci.getVirtualFileSystem(), ci.getHeaderSearchOpts(), ci.getCodeGenOpts(),
510-
ci.getTargetOpts(), ci.getLangOpts(), ci.getFrontendOpts(), nullptr));
558+
ci.getTargetOpts(), ci.getLangOpts(), ci.getFrontendOpts(), inFile,
559+
nullptr));
511560
return std::make_unique<MultiplexConsumer>(std::move(Consumers));
512561
}
513562

clang/lib/CodeGen/CGBuiltin.cpp

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,9 +134,28 @@ static Value *EmitTargetArchBuiltinExpr(CodeGenFunction *CGF,
134134
}
135135
}
136136

137+
static bool isNonTSBuiltinDispatchedToTarget(unsigned BuiltinID) {
138+
switch (BuiltinID) {
139+
case Builtin::BI__builtin_cpu_supports:
140+
case Builtin::BI__builtin_cpu_is:
141+
case Builtin::BI__builtin_cpu_init:
142+
case Builtin::BI__builtin_logbf:
143+
case Builtin::BI__builtin_logb:
144+
case Builtin::BI__builtin_scalbnf:
145+
case Builtin::BI__builtin_scalbn:
146+
return true;
147+
default:
148+
return false;
149+
}
150+
}
151+
137152
Value *CodeGenFunction::EmitTargetBuiltinExpr(unsigned BuiltinID,
138153
const CallExpr *E,
139154
ReturnValueSlot ReturnValue) {
155+
if (!getContext().BuiltinInfo.isTSBuiltin(BuiltinID) &&
156+
!isNonTSBuiltinDispatchedToTarget(BuiltinID))
157+
return nullptr;
158+
140159
if (getContext().BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
141160
assert(getContext().getAuxTargetInfo() && "Missing aux target info");
142161
return EmitTargetArchBuiltinExpr(
@@ -2628,9 +2647,31 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
26282647
// disable the specialized emitting below. Ideally we should communicate the
26292648
// rename in IR, or at least avoid generating the intrinsic calls that are
26302649
// likely to get lowered to the renamed library functions.
2631-
const unsigned BuiltinIDIfNoAsmLabel =
2650+
unsigned BuiltinIDIfNoAsmLabel =
26322651
FD->hasAttr<AsmLabelAttr>() ? 0 : BuiltinID;
26332652

2653+
if (BuiltinIDIfNoAsmLabel) {
2654+
bool HasCustomTypeChecking =
2655+
llvm::StringRef(getContext().BuiltinInfo.getAttributesString(
2656+
BuiltinIDIfNoAsmLabel))
2657+
.contains('t');
2658+
ASTContext::GetBuiltinTypeError Error;
2659+
QualType BuiltinTy =
2660+
getContext().GetBuiltinType(BuiltinIDIfNoAsmLabel, Error);
2661+
if (!Error && !HasCustomTypeChecking) {
2662+
if (const auto *Proto = BuiltinTy->getAs<FunctionProtoType>()) {
2663+
unsigned MinRequiredArgs = Proto->getNumParams();
2664+
unsigned GivenArgs = E->getNumArgs();
2665+
bool HasVariadic = Proto->isVariadic();
2666+
if ((!HasVariadic && GivenArgs != MinRequiredArgs) ||
2667+
(HasVariadic && GivenArgs < MinRequiredArgs)) {
2668+
BuiltinIDIfNoAsmLabel = 0;
2669+
BuiltinID = 0;
2670+
}
2671+
}
2672+
}
2673+
}
2674+
26342675
std::optional<bool> ErrnoOverriden;
26352676
// ErrnoOverriden is true if math-errno is overriden via the
26362677
// '#pragma float_control(precise, on)'. This pragma disables fast-math,

clang/lib/CodeGen/CGExpr.cpp

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6063,6 +6063,21 @@ static CGCallee EmitDirectCallee(CodeGenFunction &CGF, GlobalDecl GD) {
60636063
}
60646064
}
60656065

6066+
if (builtinID) {
6067+
ASTContext &Ctx = CGF.getContext();
6068+
if (Ctx.BuiltinInfo.isPredefinedLibFunction(builtinID) &&
6069+
!FD->getDeclContext()->isStdNamespace()) {
6070+
ASTContext::GetBuiltinTypeError Error;
6071+
QualType BuiltinTy = Ctx.GetBuiltinType(builtinID, Error);
6072+
if (!Error &&
6073+
!Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
6074+
Ctx.getCanonicalType(BuiltinTy),
6075+
Ctx.getCanonicalType(FD->getType()))) {
6076+
builtinID = 0;
6077+
}
6078+
}
6079+
}
6080+
60666081
if (builtinID) {
60676082
std::string NoBuiltinFD = ("no-builtin-" + FD->getName()).str();
60686083
std::string NoBuiltins = "no-builtins";

0 commit comments

Comments
 (0)