Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
430 changes: 430 additions & 0 deletions flang-rt/lib/runtime/character.cpp

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions flang/include/flang/Optimizer/Builder/IntrinsicCall.h
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,7 @@ struct IntrinsicLibrary {
fir::ExtendedValue genTeamNumber(mlir::Type,
llvm::ArrayRef<fir::ExtendedValue>);
mlir::Value genTime(mlir::Type, llvm::ArrayRef<mlir::Value>);
void genTokenize(llvm::ArrayRef<fir::ExtendedValue>);
mlir::Value genTrailz(mlir::Type, llvm::ArrayRef<mlir::Value>);
fir::ExtendedValue genTransfer(mlir::Type,
llvm::ArrayRef<fir::ExtendedValue>);
Expand Down
16 changes: 16 additions & 0 deletions flang/include/flang/Optimizer/Builder/Runtime/Character.h
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,22 @@ mlir::Value genVerify(fir::FirOpBuilder &builder, mlir::Location loc, int kind,
mlir::Value setBase, mlir::Value setLen,
mlir::Value back);

/// Generate call to TOKENIZE runtime (Form 1).
/// Splits \p stringBox into tokens based on separator characters in \p setBox.
/// \p tokensBox must be an unallocated allocatable array that receives the
/// token substrings. \p separatorBox is optional and receives separator chars.
void genTokenize(fir::FirOpBuilder &builder, mlir::Location loc,
mlir::Value tokensBox, mlir::Value separatorBox,
mlir::Value stringBox, mlir::Value setBox);

/// Generate call to TOKENIZE runtime (Form 2).
/// Returns token positions rather than substrings.
/// \p firstBox and \p lastBox must be unallocated allocatable integer arrays
/// that receive the starting and ending positions of each token.
void genTokenizePositions(fir::FirOpBuilder &builder, mlir::Location loc,
mlir::Value firstBox, mlir::Value lastBox,
mlir::Value stringBox, mlir::Value setBox);

} // namespace fir::runtime

#endif // FORTRAN_OPTIMIZER_BUILDER_RUNTIME_CHARACTER_H
7 changes: 7 additions & 0 deletions flang/include/flang/Runtime/character.h
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,13 @@ std::size_t RTDECL(Verify4)(const char32_t *, std::size_t, const char32_t *set,
void RTDECL(Verify)(Descriptor &result, const Descriptor &string,
const Descriptor &set, const Descriptor *back /*can be null*/, int kind,
const char *sourceFile = nullptr, int sourceLine = 0);

void RTDECL(Tokenize)(Descriptor &tokens, Descriptor *separator,
const Descriptor &string, const Descriptor &set,
const char *sourceFile = nullptr, int sourceLine = 0);
void RTDECL(TokenizePositions)(Descriptor &first, Descriptor &last,
const Descriptor &string, const Descriptor &set,
const char *sourceFile = nullptr, int sourceLine = 0);
}
} // namespace Fortran::runtime
#endif // FORTRAN_RUNTIME_CHARACTER_H_
107 changes: 106 additions & 1 deletion flang/lib/Evaluate/intrinsics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
#include "flang/Support/Fortran.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <climits>
#include <cmath>
#include <map>
#include <string>
Expand Down Expand Up @@ -1743,6 +1744,26 @@ static const IntrinsicInterface intrinsicSubroutine[]{
{{"seconds", AnyInt, Rank::scalar, Optionality::required,
common::Intent::In}},
{}, Rank::elemental, IntrinsicClass::impureSubroutine},
{"tokenize",
{{"string", SameCharNoLen, Rank::scalar, Optionality::required,
common::Intent::In},
{"set", SameCharNoLen, Rank::scalar, Optionality::required,
common::Intent::In},
{"tokens", SameCharNoLen, Rank::vector, Optionality::required,
common::Intent::Out},
{"separator", SameCharNoLen, Rank::vector, Optionality::optional,
common::Intent::Out}},
{}, Rank::elemental, IntrinsicClass::pureSubroutine},
{"tokenize",
{{"string", SameCharNoLen, Rank::scalar, Optionality::required,
common::Intent::In},
{"set", SameCharNoLen, Rank::scalar, Optionality::required,
common::Intent::In},
{"first", AnyInt, Rank::vector, Optionality::required,
common::Intent::Out},
{"last", AnyInt, Rank::vector, Optionality::required,
common::Intent::Out}},
{}, Rank::elemental, IntrinsicClass::pureSubroutine},
{"unlink",
{{"path", DefaultChar, Rank::scalar, Optionality::required,
common::Intent::In},
Expand Down Expand Up @@ -3496,6 +3517,24 @@ static bool ApplySpecificChecks(SpecificCall &call, FoldingContext &context) {
arg ? arg->sourceLocation() : context.messages().at(),
"Argument of LOC() must be an object or procedure"_err_en_US);
}
} else if (name == "tokenize") {
// Both forms of TOKENIZE have at least 4 dummy arguments, and the last two
// must be allocatable.
const auto &dummies{
call.specificIntrinsic.characteristics.value().dummyArguments};
for (int i{2}; i < 4; ++i) {
const auto &arg{call.arguments[i]};
if (arg) {
if (const auto *expr{arg->UnwrapExpr()}) {
if (!IsAllocatableDesignator(*expr)) {
ok = false;
context.messages().Say(arg->sourceLocation(),
"'%s=' argument to 'tokenize' must be ALLOCATABLE"_err_en_US,
dummies[i].name);
}
}
}
}
}
return ok;
}
Expand Down Expand Up @@ -3556,15 +3595,81 @@ std::optional<SpecificCall> IntrinsicProcTable::Implementation::Probe(
}
}

// Find the specific subroutine and match the actual arguments against its
// dummy argument patterns. If there are multiple specific subroutines with
// the same name, try them in order. If one matches, clear out the errors.
// If none match, keep the messages from the form whose dummy argument
// types and keywords best match the actual arguments supplied.
if (call.isSubroutineCall) {
const std::string &name{ResolveAlias(call.name)};
auto subrRange{subroutines_.equal_range(name)};
parser::Messages subrErrors;
int bestScore{INT_MIN};
parser::Messages localBuffer;
parser::Messages *finalBuffer{context.messages().messages()};
parser::ContextualMessages localMessages{
context.messages().at(), finalBuffer ? &localBuffer : nullptr};
FoldingContext localContext{context, localMessages};
for (auto iter{subrRange.first}; iter != subrRange.second; ++iter) {
if (auto specificCall{iter->second->Match(
call, defaults_, arguments, context, builtinsScope_)}) {
call, defaults_, arguments, localContext, builtinsScope_)}) {
if (finalBuffer) {
finalBuffer->Annex(std::move(localBuffer));
}
ApplySpecificChecks(*specificCall, context);
return specificCall;
}
// Match failed. Compute a score reflecting how well the actual
// arguments correspond to this form's dummy arguments: count the
// number of positional arguments whose type category matches the
// corresponding dummy's expected categories, plus the number of
// keyword arguments whose keyword name matches a dummy in this form,
// minus the number of required dummies that cannot be satisfied by
// the number of arguments provided. Keep the error messages from
// the form with the highest score, preferring an earlier form on
// ties.
const auto *iface{iter->second};
int dummyCount{iface->CountArguments()};
int numRequired{0};
for (int j{0}; j < dummyCount; ++j) {
if (iface->dummy[j].optionality == Optionality::required) {
++numRequired;
}
}
int score{0};
int positionalIndex{0};
for (const auto &arg : arguments) {
if (arg) {
if (auto kw{arg->keyword()}) {
for (int k{0}; k < dummyCount; ++k) {
if (kw == iface->dummy[k].keyword) {
++score;
break;
}
}
} else {
if (positionalIndex < dummyCount) {
if (auto type{arg->GetType()}) {
if (iface->dummy[positionalIndex].typePattern.categorySet.test(
type->category())) {
++score;
}
}
}
++positionalIndex;
}
}
}
score -= std::max(0, numRequired - static_cast<int>(arguments.size()));
if (score > bestScore) {
bestScore = score;
subrErrors = std::move(localBuffer);
} else {
localBuffer.clear();
}
}
if (finalBuffer) {
finalBuffer->Annex(std::move(subrErrors));
}
if (IsIntrinsicFunction(call.name) && !IsDualIntrinsic(call.name)) {
context.messages().Say(
Expand Down
102 changes: 102 additions & 0 deletions flang/lib/Optimizer/Builder/IntrinsicCall.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -785,6 +785,13 @@ static constexpr IntrinsicHandler handlers[]{
{"team", asBox, handleDynamicOptional}}},
/*isElemental=*/false},
{"time", &I::genTime, {}, /*isElemental=*/false},
{"tokenize",
&I::genTokenize,
{{{"string", asAddr},
{"set", asAddr},
{"out1", asInquired},
{"out2", asInquired, handleDynamicOptional}}},
/*isElemental=*/false},
{"trailz", &I::genTrailz},
{"transfer",
&I::genTransfer,
Expand Down Expand Up @@ -8393,6 +8400,101 @@ void IntrinsicLibrary::genSleep(llvm::ArrayRef<fir::ExtendedValue> args) {
fir::runtime::genSleep(builder, loc, fir::getBase(args[0]));
}

// TOKENIZE
void IntrinsicLibrary::genTokenize(llvm::ArrayRef<fir::ExtendedValue> args) {
assert(args.size() == 4 && "TOKENIZE requires 3 or 4 arguments");

const fir::ExtendedValue &string = args[0];
const fir::ExtendedValue &set = args[1];

// Distinguish forms by the element type of the third argument. For form 1,
// TOKENS is CHARACTER. For form 2, FIRST is INTEGER.
mlir::Type thirdArgEleTy = fir::getElementTypeOf(args[2]);
bool isForm1 = fir::isa_char(thirdArgEleTy);
bool isForm2 = fir::isa_integer(thirdArgEleTy);
assert((isForm1 || isForm2) &&
"TOKENIZE third argument must be CHARACTER or INTEGER");

mlir::Value stringBox = builder.createBox(loc, string);
mlir::Value setBox = builder.createBox(loc, set);

mlir::Type boxNoneTy = fir::BoxType::get(builder.getNoneType());
mlir::Type boxNoneRefTy = fir::ReferenceType::get(boxNoneTy);

// A lambda to return the address of the descriptor storage to pass to the
// runtime. For MutableBoxValue, this also handles any required syncing
// before/after the runtime call.
auto getBoxStorageAddr =
[&](const fir::ExtendedValue &exv, llvm::StringRef what,
const fir::MutableBoxValue **mutableBoxOut) -> mlir::Value {
if (const auto *mb = exv.getBoxOf<fir::MutableBoxValue>()) {
if (mutableBoxOut)
*mutableBoxOut = mb;
mlir::Value addr = fir::factory::getMutableIRBox(builder, loc, *mb);
return builder.createConvert(loc, boxNoneRefTy, addr);
}
if (const auto *bv = exv.getBoxOf<fir::BoxValue>()) {
mlir::Value addr = bv->getAddr();
if (auto boxTy = fir::dyn_cast_ptrEleTy(addr.getType())) {
if (mlir::isa<fir::BaseBoxType>(boxTy))
return builder.createConvert(loc, boxNoneRefTy, addr);
}
fir::emitFatalError(loc, llvm::Twine("TOKENIZE: ") + what +
" must be a descriptor address");
}
fir::emitFatalError(loc, llvm::Twine("TOKENIZE: ") + what +
" not lowered as a boxed entity");
};

if (isForm1) {
// Form 1: TOKENIZE(STRING, SET, TOKENS [, SEPARATOR])
const fir::ExtendedValue &tokens = args[2];
const fir::MutableBoxValue *tokensMutableBox{nullptr};
mlir::Value tokensBoxAddr =
getBoxStorageAddr(tokens, "TOKENS", &tokensMutableBox);

// Handle optional SEPARATOR argument
mlir::Value separatorBoxAddr;
const fir::MutableBoxValue *separatorMutableBox{nullptr};
if (!isStaticallyAbsent(args[3])) {
const fir::ExtendedValue &separator = args[3];
separatorBoxAddr =
getBoxStorageAddr(separator, "SEPARATOR", &separatorMutableBox);
} else {
separatorBoxAddr = builder.createNullConstant(loc, boxNoneRefTy);
}

// Call the Form 1 runtime function
fir::runtime::genTokenize(builder, loc, tokensBoxAddr, separatorBoxAddr,
stringBox, setBox);

if (tokensMutableBox)
fir::factory::syncMutableBoxFromIRBox(builder, loc, *tokensMutableBox);
if (separatorMutableBox)
fir::factory::syncMutableBoxFromIRBox(builder, loc, *separatorMutableBox);

} else {
// Form 2: TOKENIZE(STRING, SET, FIRST, LAST)
const fir::ExtendedValue &first = args[2];
const fir::ExtendedValue &last = args[3];

const fir::MutableBoxValue *firstMutableBox{nullptr};
const fir::MutableBoxValue *lastMutableBox{nullptr};
mlir::Value firstBoxAddr =
getBoxStorageAddr(first, "FIRST", &firstMutableBox);
mlir::Value lastBoxAddr = getBoxStorageAddr(last, "LAST", &lastMutableBox);

// Call the Form 2 runtime function
fir::runtime::genTokenizePositions(builder, loc, firstBoxAddr, lastBoxAddr,
stringBox, setBox);

if (firstMutableBox)
fir::factory::syncMutableBoxFromIRBox(builder, loc, *firstMutableBox);
if (lastMutableBox)
fir::factory::syncMutableBoxFromIRBox(builder, loc, *lastMutableBox);
}
}

// TRANSFER
fir::ExtendedValue
IntrinsicLibrary::genTransfer(mlir::Type resultType,
Expand Down
29 changes: 29 additions & 0 deletions flang/lib/Optimizer/Builder/Runtime/Character.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,35 @@ void fir::runtime::genVerifyDescriptor(fir::FirOpBuilder &builder,
kind);
}

void fir::runtime::genTokenize(fir::FirOpBuilder &builder, mlir::Location loc,
mlir::Value tokensBox, mlir::Value separatorBox,
mlir::Value stringBox, mlir::Value setBox) {
auto func = fir::runtime::getRuntimeFunc<mkRTKey(Tokenize)>(loc, builder);
auto fTy = func.getFunctionType();
auto sourceFile = fir::factory::locationToFilename(builder, loc);
auto sourceLine =
fir::factory::locationToLineNo(builder, loc, fTy.getInput(5));
auto args =
fir::runtime::createArguments(builder, loc, fTy, tokensBox, separatorBox,
stringBox, setBox, sourceFile, sourceLine);
fir::CallOp::create(builder, loc, func, args);
}

void fir::runtime::genTokenizePositions(
fir::FirOpBuilder &builder, mlir::Location loc, mlir::Value firstBox,
mlir::Value lastBox, mlir::Value stringBox, mlir::Value setBox) {
auto func =
fir::runtime::getRuntimeFunc<mkRTKey(TokenizePositions)>(loc, builder);
auto fTy = func.getFunctionType();
auto sourceFile = fir::factory::locationToFilename(builder, loc);
auto sourceLine =
fir::factory::locationToLineNo(builder, loc, fTy.getInput(5));
auto args =
fir::runtime::createArguments(builder, loc, fTy, firstBox, lastBox,
stringBox, setBox, sourceFile, sourceLine);
fir::CallOp::create(builder, loc, func, args);
}

mlir::Value fir::runtime::genVerify(fir::FirOpBuilder &builder,
mlir::Location loc, int kind,
mlir::Value stringBase,
Expand Down
27 changes: 27 additions & 0 deletions flang/test/Lower/Intrinsics/tokenize.f90
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
! RUN: %flang_fc1 -emit-hlfir %s -o - | FileCheck %s

! CHECK-LABEL: tok_form1
subroutine tok_form1()
implicit none
character(:), allocatable :: tokens(:)
call tokenize("a,b", ",", tokens)
! CHECK-DAG: %[[TOKENS:.*]] = fir.alloca !fir.box<!fir.heap<!fir.array<?x!fir.char<1,?>>>>
! CHECK-DAG: %[[TOKENS_DECL:.*]]:2 = hlfir.declare %[[TOKENS]] {fortran_attrs = #fir.var_attrs<allocatable>
! CHECK-DAG: %[[TOKENS_NONE:.*]] = fir.convert %[[TOKENS_DECL]]#0 : (!fir.ref<!fir.box<!fir.heap<!fir.array<?x!fir.char<1,?>>>>>) -> !fir.ref<!fir.box<none>>
! CHECK-DAG: %[[SEP_NONE:.*]] = fir.zero_bits !fir.ref<!fir.box<none>>
! CHECK: fir.call @_FortranATokenize(%[[TOKENS_NONE]], %[[SEP_NONE]],
end subroutine tok_form1

! CHECK-LABEL: tok_form2
subroutine tok_form2()
implicit none
integer, allocatable :: first(:), last(:)
call tokenize("a,,b", ",", first, last)
! CHECK-DAG: %[[FIRST:.*]] = fir.alloca !fir.box<!fir.heap<!fir.array<?xi32>>>
! CHECK-DAG: %[[LAST:.*]] = fir.alloca !fir.box<!fir.heap<!fir.array<?xi32>>>
! CHECK-DAG: %[[FIRST_DECL:.*]]:2 = hlfir.declare %[[FIRST]] {fortran_attrs = #fir.var_attrs<allocatable>
! CHECK-DAG: %[[LAST_DECL:.*]]:2 = hlfir.declare %[[LAST]] {fortran_attrs = #fir.var_attrs<allocatable>
! CHECK-DAG: %[[FIRST_NONE:.*]] = fir.convert %[[FIRST_DECL]]#0 : (!fir.ref<!fir.box<!fir.heap<!fir.array<?xi32>>>>) -> !fir.ref<!fir.box<none>>
! CHECK-DAG: %[[LAST_NONE:.*]] = fir.convert %[[LAST_DECL]]#0 : (!fir.ref<!fir.box<!fir.heap<!fir.array<?xi32>>>>) -> !fir.ref<!fir.box<none>>
! CHECK: fir.call @_FortranATokenizePositions(%[[FIRST_NONE]], %[[LAST_NONE]],
end subroutine tok_form2
Loading